Excel 列比较使用 python 代码

Excel columns comparison using python code

我正在使用 excel 来比较三列:我的想法是将两列数据与作为数组的第三列进行比较,就像第三列中的每个值都应该与第一列和第二列,并且只想提取第一列和第二列的数据出现在第三列中的那些行我使用了这个 python 命令

if([x in x,y for datafile] == [x in x for file) and [y in x,y for datafile] == [x in x for file]): 
    print x,y
else:
    print none        

这给了我一个语法错误

我已经使用 zip 函数将我的前两列转换为元组 x,y 对应于元组中的值

Col_1 ||  Col_2    ||   file
Abc   |    Abk     |    cnl
Nck   |    Nck     |    Abk
xkl   |    cnl     |    Abc  
mzn   |    mzn     |  

这个我合并成了数据文件((Abc,Abk),(Nck,Nck),(xkl,cnl),(mzn,mzn))

注意:我的第 3 列的值小于第 1 列和第 2 列的值。我有超过 100k 个值要比较

我想要一个用于此查询的工作 python 程序

if [x for x,y in mydata if x == genelist and
y for x,y in mydata if y == genelist]:
    print (x,y)
else: 

谁能更正上面代码中的语法错误

mydata('gene1,genea','gene2,geneb''gene3,genec') and genelist ('genea','geneb','genec') 

当我使用不带 if 语句的代码时,它会打印出“[]”,我不知道这里出了什么问题

您可以使用 pandas.Series.isin 过滤它:

你的 excel 数据 (eg:comparison.xlsx) :

使用:

import pandas as pd
df = pd.read_excel('comparison.xlsx')
result = df[df['finaldata1'].isin(list(df['check'])) & df['finaldata2'].isin(list(df['check']))]
result

它会给你:

    finaldata1  finaldata2  check
0   Abc         Abk         cnl

因为 AbcAbkfile 列中。

更新:将结果写入excel文件:

from pandas import ExcelWriter

writer = ExcelWriter('PythonExport.xlsx')
result.to_excel(writer,'Sheet1',index=False)
writer.save()

结果将写入 excel 文件 PythonExport.xlsx: