Python Pandas DataFrames:逐行比较两行.

我想比较两个表中的行,只保留类似的匹配.

import pandas as pd
df = pd.DataFrame.from_items([('a', [0,1,1,0]), ('b', [0,0,1,1]),('c',[1,0,0,1]), ('d',[1,0,1,0])], orient='index', columns=['A', 'B', 'C', 'D'])
df

   A  B  C  D
a  0  1  1  0
b  0  0  1  1
c  1  0  0  1
d  1  0  1  0

并在此表中进行转换:

     A  B  C  D
a/b  0  0  1  0
a/c  0  0  0  0
a/d  0  0  1  0
a/d  0  0  0  0
b/c  0  0  0  1
b/d  0  0  1  0
c/d  1  0  0  0
最佳答案
您可以使用itertools迭代所有行组合以创建一组新项目,如下所示:

import itertools
new_items = [('{}/{}'.format(i1, i2), r1 * r2) 
                for (i1, r1), (i2, r2) in itertools.combinations(df.iterrows(), 2)]
transformed = pd.DataFrame.from_items(new_items, orient='index', columns=['A', 'B', 'C', 'D'])

转载注明原文:Python Pandas DataFrames:逐行比较两行. - 代码日志