簡體   English   中英

Python Pandas DataFrames:逐行比較兩行。

[英]Python Pandas DataFrames: Compare rows two by two recusively.

我想比較兩個表中的行,只保留類似的匹配。

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'])

說明

  • 首先要做的是生成一種迭代每個組合的機制。 我選擇了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

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM