使用熊猫比较单元格迭代

时间:2021-01-19 21:48:45

标签: python pandas

我正在尝试使用 Pandas 比较数据框中的单元格。 数据看起来像这样:

seqnames, start, end, width, strand, s1, s2, s3, sn
1, Ha412HOChr01, 1, 220000, 220000, CN2, CN10, CN2, CN2
2, Ha412HOChr01, 1, 220000, 220000, CN2, CN2, CN2, CN2
3, Ha412HOChr01, 1, 220000, 220000, CN2, CN4, CN2, CN2
n, Ha412HOChr01, 1, 220000, 220000, CN2, CN2, CN2, CN6

我能够使用以下代码进行单独比较

import pandas as pd

df = pd.read_csv("test.csv") 

if df.iloc[0,5] != df.iloc[0,6]:
  print("yay!")
else:
  print("not intersting...")

我想在循环中逐行或以任何其他更有效的方法迭代 s1 和所有其他 s 列之间的比较。 当我尝试以下代码时:

df = pd.read_csv("test.csv") 
df.columns
#make sure to change in future analysis
ref = df[' Sunflower_14_S8']
all_the_rest = df.drop(['seqnames', ' start', ' end', ' width', ' strand'], axis=1)
#all_the_rest.columns

OP = ref.eq(all_the_rest)
OP.to_csv("OP.csv")

我有一个有线输出

0,False,False,False,False,False,False,False,False,False,False,False,False,False
1,False,False,False,False,False,False,False,False,False,False,False,False,False
2,False,False,False,False,False,False,False,False,False,False,False,False,False
3,False,False,False,False,False,False,False,False,False,False,False,False,False444,False,False,False,False,False,False,False,False,False,False,False,False,False

它似乎比较所有字符而不是字符串 我是编程新手,遇到了困难,感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

这有帮助吗?

import pandas as pd
# define a list of columns you want to compare
cols = ['s1', 's2', 's3']
# some sample data
df = pd.DataFrame(columns=cols)
df['s1'] = ['CN2', 'CN10', 'CN2', 'CN2']
df['s2'] = ['CN2', 'CN2', 'CN2', 'CN2']
df['s3'] = ['CN2', 'CN2', 'CN2', 'CN6']
# remove 's1' from the list of columns
cols_except_s1 = [x for x in cols if x!='s1']
# create a blank dataframe to hold our comparisons
df_comparison = pd.DataFrame(columns=cols_except_s1)
# iterate through each other column, comparing it against 's1'
for x in cols_except_s1:
    comparison_series = df['s1'] == df[x]
    df_comparison[x] = comparison_series
# the result is a dataframe that has columns of Boolean values
print(df_comparison)

输出

    s2  s3
0   True    True
1   False   False
2   True    True
3   True    False

答案 1 :(得分:0)

9 小时后,我找到了一种不使用 panadas 的方法......

df = pd.read_csv("test.csv")
#df.columns
#convertthe data frame to a list
list = df.values.tolist()
for line in list:
  lineAVG = sum(line[5:]) / len(line[5:])
  ref = (line[5])

  if lineAVG - ref > 0.15:
    output = line
    print(output)