Python Pandas 数据框:递归地两两比较行。

3
我希望能够逐行比较两个表格,并仅保留相似的匹配项。
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
2个回答

3
你可以使用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'])

3

解释

  • 首先要做的是生成一个迭代每个组合的机制。我选择了np.triu_indices。这是numpy让我能够访问正方形矩阵的上三角的方法。@Michael使用itertools.combinations完成此操作。
  • 接下来要处理的事情是格式化索引。@Michael和我都使用'{}/{}'.format
  • 最后,我们需要将它们全部放在一起。我使用pd.concat,@Michael使用pd.DataFrame.ftom_items
  • 我喜欢@Michael的答案,我认为比我的更好。下次回答类似的问题时,我可能会使用两种方法的组合。
  • 我通常避免使用itertools,虽然我没有很好的理由。也许我应该:-)
  • 为了更详细的解释,我鼓励您逐行运行此代码,并查看各个组件的外观。

tups = zip(*np.triu_indices(df.shape[0], 1))
rnm = '{}/{}'.format
pd.concat(
    [df.iloc[i].mul(df.iloc[j]).rename(rnm(*df.index[[i, j]])) for i, j in tups],
     axis=1).T

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接