【问题标题】:Excel columns comparison using python code使用python代码比较Excel列
【发布时间】:2017-10-13 16:39:19
【问题描述】:

我正在使用 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 列。我有超过 10 万个值要比较

我想要这个查询的工作 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 语句的代码时,它会打印出“[]”我不知道这里出了什么问题

【问题讨论】:

    标签: python excel data-comparison


    【解决方案1】:

    您可以使用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

    【讨论】:

    • Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win32 输入“copyright”、“credits”或“license( )“ 了解更多信息。 >>> import pandas as pd >>> import xlrd >>> df = pd.read_excel('Book1.xlsx') >>> result = df[df['finaldata'].isin(list[df['check' ]])] 回溯(最近一次调用最后):文件“”,第 1 行,在 结果 = df[df['finaldata'].isin(list[df['check']] )] TypeError: 'type' 对象没有属性 'getitem'
    • 你的结果不正确,应该是result = df[df['finaldata'].isin(list(df['check']))] 不是 result = df[df['finaldata'].isin(list[df['check']])],在list之后改成()而不是[]
    • 空数据帧列:[finaldata, check] 索引:[]
    • 您确定您的df 中有数据吗?看来你的df 是空的
    • 数据仍然存在,程序允许与一列进行比较,但我想将两列数据与数据数组/列表进行比较
    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多