在python中比较数据帧中的两行时查找公共列

时间:2016-05-16 16:18:21

标签: python pandas dataframe

我有一个以下结构的数据框。我希望在比较两行时得到具有相同值(对于特定值)的列号。

1 1 0 1 1
0 1 0 1 0
0 1 0 0 1
1 0 0 0 1
0 0 0 0 0
1 0 0 0 1

因此,例如当我使用上面的示例df来比较两行来获取其中包含1的列时,我应该在比较row(0)和row(1)时得到col(1)和col(3) )。类似地,当我比较row(1)和row(2)时,我应该得到col(1)。我想知道python中是否有更高效的解决方案。

注意:我只想要匹配的列号,我还要指定要比较的行。

2 个答案:

答案 0 :(得分:3)

考虑以下数据框:

import numpy as np
df = pd.DataFrame(np.random.binomial(1, 0.2, (2, 10000)))

它将是一个大小为2x10000的二进制矩阵。

np.where((df.iloc[0] * df.iloc[1])) 

或者,

np.where((df.iloc[0]) & (df.iloc[1]))

返回两行中包含1的列。乘法似乎更快:

%timeit np.where((df.iloc[0]) & (df.iloc[1]))
1000 loops, best of 3: 400 µs per loop

%timeit np.where((df.iloc[0] * df.iloc[1]))
1000 loops, best of 3: 269 µs per loop

答案 1 :(得分:0)

这是一个简单的功能。您可以根据需要进行修改,具体取决于您表示数据的方式。我假设一份清单:

df = [[1,1,0,1,1],
      [0,1,0,1,0],
      [0,1,0,0,1],
      [1,0,0,0,1],
      [0,0,0,0,0],
      [1,0,0,0,1]]

def compare_rows(df,row1,row2):
    """Returns the column numbers in which both rows contain 1's"""
    column_numbers = []
    for i,_ in enumerate(df[0]):
        if (df[row1][i] == 1) and (df[row2][i] ==1):
            column_numbers.append(i)
    return column_numbers

compare_rows(df,0,1)生成输出:

[1,3]

相关问题