【问题标题】:Comparing two dataframes of different length row by row and adding columns for each row with equal value逐行比较两个不同长度的数据帧,并为每行添加相等值的列
【发布时间】:2016-01-03 12:59:33
【问题描述】:

我在 python pandas 中有两个不同长度的数据框,如下所示:

df1:                                 df2:

      Column1  Column2 Column3            ColumnA ColumnB 
    0    1       a       r              0    1       a
    1    2       b       u              1    1       d
    2    3       c       k              2    1       e
    3    4       d       j              3    2       r
    4    5       e       f              4    2       w
                                        5    3       y 
                                        6    3       h

我现在要做的是比较 df1 的 Column1 和 df2 的 ColumnA。对于每个“命中”,其中 df2 中的 ColumnA 中的一行与 df1 中 Column1 中的一行具有相同的值,我想将一列附加到 df1,其中 df2 的 ColumnB 具有“命中”所在的行,所以我的结果如下所示:

df1:

   Column1  Column2  Column3  Column4 Column5  Column6
0     1        a        r        a       d        e
1     2        b        u        r       w
2     3        c        k        y       h
3     4        d        j
4     5        e        f

到目前为止我尝试过的是:

for row in df1, df2:
   if df1[Column1] == df2[ColumnA]:
      print 'yey!'

这给了我一个错误,说我无法比较两个不同长度的数据帧。所以我尝试了:

for row in df1, df2:
    if def2[def2['ColumnA'].isin(def1['column1'])]:
        print 'lalala' 
    else:
        print 'Nope'

就我获得输出而言,哪个“有效”,但我认为它不会遍历行并比较它们,因为它只打印两次“lalala”。于是我又研究了一番,找到了一种遍历数据框每一行的方法,即:

for index, row in df1.iterrows():
    print row['Column1]

但我不知道如何使用它来比较两个数据框的列并获得我想要的输出。

非常感谢任何有关如何执行此操作的帮助。

【问题讨论】:

    标签: python pandas compare dataframe


    【解决方案1】:

    我建议您使用 DataFrame API,它允许在join, mergegroupby 等方面使用 DF 进行操作。您可以在下面找到我的解决方案:

    import pandas as pd
    
    df1 = pd.DataFrame({'Column1': [1,2,3,4,5], 
        'Column2': ['a','b','c','d','e'], 
        'Column3': ['r','u','k','j','f']})
    
    df2 = pd.DataFrame({'Column1': [1,1,1,2,2,3,3], 'ColumnB': ['a','d','e','r','w','y','h']})
    
    dfs = pd.DataFrame({})
    for name, group in df2.groupby('Column1'):
        buffer_df = pd.DataFrame({'Column1': group['Column1'][:1]})
        i = 0
        for index, value in group['ColumnB'].iteritems():
            i += 1
            string = 'Column_' + str(i)
            buffer_df[string] = value
    
        dfs = dfs.append(buffer_df)
    
    result = pd.merge(df1, dfs, how='left', on='Column1')
    print(result)
    

    结果是:

       Column1 Column2 Column3 Column_0 Column_1 Column_2
    0        1       a       r        a        d        e
    1        2       b       u        r        w      NaN
    2        3       c       k        y        h      NaN
    3        4       d       j      NaN      NaN      NaN
    4        5       e       f      NaN      NaN      NaN
    

    附:更多详情:

    1) 对于 df2,我通过“Column1”生成 groups。单个 group 是一个数据框。示例如下:

       Column1 ColumnB
    0        1       a
    1        1       d
    2        1       e
    

    2) 对于每个 group 我生成数据帧 buffer_df:

       Column1 Column_0 Column_1 Column_2
    0        1        a        d        e
    

    3) 之后我创建 DF dfs:

       Column1 Column_0 Column_1 Column_2
    0        1        a        d        e
    3        2        r        w      NaN
    5        3        y        h      NaN
    

    4) 最后我为 df1dfs 执行左连接以获得所需的结果。

    2)* buffer_df 是迭代产生的:

    step0 (buffer_df = pd.DataFrame({'Column1': group['Column1'][:1]})):
                Column1
             5       3
    
    step1 (buffer_df['Column_0'] = group['ColumnB'][5]):      
                Column1 Column_0
             5       3       y
    
    step2 (buffer_df['Column_1'] = group['ColumnB'][5]):      
                Column1 Column_0 Column_1
             5       3       y       h
    

    【讨论】:

    • 谢谢你,一个非常简洁的答案!但是我注意到我不太明白你在做什么,从 buffer_df = .... 直到 dfs = dfs.append(buffer_df)。你能解释一下代码的作用吗?谢谢!
    • 实际上我想我知道单行代码的作用,但我不知道它们如何协同工作来创建输出......
    • @sequence_hard 再次检查我的答案:添加了新的详细信息。这个过程对你来说变得更清楚了吗?
    • 是的,现在很清楚了,谢谢你这么详细的回答。我昨天要脑死了,这就是我迟到的原因。但是,当我尝试将脚本用于我的实际数据(其结构类似于示例数据,只是每个 df 中有更多列和混合字符串/整数值)时,我收到以下错误:第 33 行,在 buffer_df[string] = group['Gene'][iter] KeyError: 83 知道这可能是什么原因吗?
    • 从此:文件“index.pyx”,第 97 行,在 pandas.index.IndexEngine.get_value (pandas/index.c:2679) 文件“index.pyx”,第 105 行,在 pandas .index.IndexEngine.get_value (pandas/index.c:2494) 文件“index.pyx”,第 149 行,在 pandas.index.IndexEngine.get_loc (pandas/index.c:3233) 文件“hashtable.pyx”,行381,在 pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:7032) 文件“hashtable.pyx”,第 387 行,在 pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6973) KeyError: 83 is也是错误消息的一部分,我想我的文件索引可能有问题...
    猜你喜欢
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多