Python:如何在熊猫中将列彼此相乘?

时间:2019-05-07 09:59:17

标签: python pandas

假设有一个数据帧df,如下所示:

df
   A   B   C
0  2   3   1
1  1   0   1
2  0   2   1
3  1   2   2

我想添加列作为列之间的乘法,并且具有类似的内容

df
   A   B   C   AB  AC  BC
0  2   3   1   6   2   3 
1  1   0   1   0   1   0
2  0   2   1   0   0   2
3  1   2   2   2   2   4

4 个答案:

答案 0 :(得分:2)

这里的一种方法是使用itertools.combinations获取列名组合,并将其乘积包含在列表理解中:

from itertools import combinations
combs = list(map(list,list(combinations(df.columns.tolist(), 2))))
# [['A', 'B'], ['A', 'C'], ['B', 'C']]
new_cols = pd.concat([df[c].prod(1) for c in combs], axis=1)
new_cols.columns = [''.join(i) for i in combs]
df.assign(**new_cols)

   A  B  C  AB  AC  BC
0  2  3  1   6   2   3
1  1  0  1   0   1   0
2  0  2  1   0   0   2
3  1  2  2   2   2   4

答案 1 :(得分:1)

为了简单起见,这里我使用了基本的列操作。看看它是否对您有用:

import pandas as pd
df = pd.DataFrame({
    'A':[2,1,0,1],
    'B':[3,0,2,2],
    'C':[1,1,1,2]
})
df['AB']=df['A']*df['B']
df['AC']=df['A']*df['C']
df['BC']=df['B']*df['C']
df

输出

A   B   C   AB  AC  BC
0   2   3   1   6   2   3
1   1   0   1   0   1   0
2   0   2   1   0   0   2
3   1   2   2   2   2   4

答案 2 :(得分:1)

我认为最简单的答案是...。

from itertools import combinations
df = df.assign(**{(k1+k2): df[k1]*df[k2] for k1,k2 in combinations(df.columns,2)})

答案 3 :(得分:0)

DataFrame.reindexMultiIndex.from_tuples中使用combinations,在DataFrame.mul中使用倍数,最后在DataFrame.join中使用原始元素加入

from  itertools import combinations

c = pd.MultiIndex.from_tuples(combinations(df.columns, 2))
df1 = df.reindex(c, axis=1, level=0).mul(df.reindex(c, axis=1, level=1))
df1.columns = df1.columns.map(''.join)

df = df.join(df1)
print (df)
   A  B  C  AB  AC  BC
0  2  3  1   6   2   3
1  1  0  1   0   1   0
2  0  2  1   0   0   2
3  1  2  2   2   2   4
相关问题