[英]How can I multiply each column with the other columns of the Pandas DataFrame?
給定一個pandas數據幀,我想逐個地將每列與其他列相乘,並將每個新列作為新列返回到該數據幀。 例如
A B C
1 2 3
2 4 4
1 2 5
然后
A B C A*B A*C B*C
1 2 2 2 3 6
2 4 8 8 8 16
1 2 2 2 5 10
以下是蠻力方法,但它應該做的工作。 permutations()
生成所有列排列。 內部sorted()
和set()
合並('A','B')
和('B','A')
等。
import pandas as pd
import itertools
df = pd.DataFrame([[1,2,1],[2,4,2],[3,4,5]],columns=['A','B','C'])
for c1,c2 in sorted(set([tuple(sorted(s)) for s in itertools.permutations(df.columns,2)])):
df['{0}x{1}'.format(c1,c2)] = df[c1]*df[c2]
print df
來自itertools
combinations
itertools
您的需求:
import pandas as pd
from itertools import combinations
for c1, c2 in combinations(df.columns, 2):
df['{0}*{1}'.format(c1,c2)] = df[c1] * df[c2]
df
現在包含您想要的列:
A B C A*B A*C B*C
0 1 2 1 2 1 2
1 2 4 2 8 4 8
2 3 4 5 12 15 20
如果您不想將所有內容保存在內存中,您可以動態計算產品:
for c1, c2 in combinations(df.columns, 2):
s = df[c1] * df[c2]
# Do whatever is necessary with s
print c1, c2, s.apply(lambda x: x ** 0.5).mean()
輸出:
A B 2.56891410075
A C 2.29099444874
B C 2.90492554737
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.