繁体   English   中英

如何将每列与Pandas DataFrame的其他列相乘?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM