有 2 个形状为 (6, 4) 和 (6,2) 的数据框。需要执行 2 个数据帧的逐元素乘法。

>>> import pandas as pd
>>> df1 = pd.DataFrame({'col1' : [1,2,6,8,-1,3], 'col2' : [1,2,6,8,-1,3], 'col3' : [1,2,6,8,-1,3], 'col4' : [1,2,6,8,-1,3]})
>>> df1
   col1  col2  col3  col4
0     1     1     1     1
1     2     2     2     2
2     6     6     6     6
3     8     8     8     8
4    -1    -1    -1    -1
5     3     3     3     3
>>>
>>> df2 = pd.DataFrame({'col1' : [9,8,7,1,1,1], 'col2' : [11,12,16,2,2,1]})
>>> df2
   col1  col2
0     9    11
1     8    12
2     7    16
3     1     2
4     1     2
5     1     1

预期输出:
0     9     9       9       9
1     16    16      16      16
2     42    42      42      42
3     8     8       8       8
4     -1    -1      -1      -1
5     3     3       3       3

0   11      11      11      11
1   24      24      24      24
2   96      96      96      96
3   16      16      16      16
4   -2      -2      -2      -2
5   3       3       3       3

方法一:
a = np.array(df1.values)
b = np.array(df2.values)

尝试了以下方法,
c = a * b

错误:#ValueError:操作数无法与形状 (6, 4) 和 (6,2) 一起广播

方法二:

将 1 个数据帧转换为系列。
df_temp=df1[df1.columns.values['a']]
func = lambda x: np.asarray(x) * np.asarray(df2[df2.columns.values[0]])

df_temp.apply(func)

输出:
没有获得元素明智的输出。

方法三:

将 DF 转换为列表并乘以列表:
df11=list(df1.values.flatten())
df22=list(df2.values.flatten())

但是,结果列表不是二维的;。它的一维。

最佳答案

你应该使用 .multiply():

import pandas as pd

df1 = pd.DataFrame({'col1' : [1,2,6,8,-1,3], 'col2' : [1,2,6,8,-1,3],
    'col3' : [1,2,6,8,-1,3], 'col4' : [1,2,6,8,-1,3]})
df2 = pd.DataFrame({'col1' : [9,8,7,1,1,1], 'col2' : [11,12,16,2,2,1]})

for x in range(len(df2.columns)):
    new_df = df1.multiply(df2.iloc[:, x], axis=0)
    print new_df

这将返回:
   col1  col2  col3  col4
0     9     9     9     9
1    16    16    16    16
2    42    42    42    42
3     8     8     8     8
4    -1    -1    -1    -1
5     3     3     3     3

   col1  col2  col3  col4
0    11    11    11    11
1    24    24    24    24
2    96    96    96    96
3    16    16    16    16
4    -2    -2    -2    -2
5     3     3     3     3

关于python - 2 个数据帧的元素乘法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32414354/

10-12 17:52
查看更多