[英]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
完成此任務。 '{}/{}'.format
pd.concat
,@ Michael使用pd.DataFrame.ftom_items
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.