python - 如何在 pandas 中将 n*m DataFrame 与 1*m DataFrame 相乘?

标签 python pandas dataframe multiplication

我有 2 个要相乘的 pandas DataFrame:

frame_score: 
   Score1  Score2
0     100      80
1    -150      20
2    -110      70
3     180      99
4     125      20

frame_weights: 
   Score1  Score2
0     0.6     0.4

我试过:

import pandas as pd
import numpy as np

frame_score = pd.DataFrame({'Score1'  : [100, -150, -110, 180, 125], 
                      'Score2'  : [80,  20, 70, 99, 20]})

frame_weights = pd.DataFrame({'Score1': [0.6], 'Score2' : [0.4]})

print('frame_score: \n{0}'.format(frame_score))
print('\nframe_weights: \n{0}'.format(frame_weights))

# Each of the following alternatives yields the same results
frame_score_weighted = frame_score.mul(frame_weights, axis=0)
frame_score_weighted = frame_score * frame_weights
frame_score_weighted = frame_score.multiply(frame_weights, axis=1)

print('\nframe_score_weighted: \n{0}'.format(frame_score_weighted))

返回:

frame_score_weighted:   
    Score1  Score2
0    60.0    32.0
1     NaN     NaN
2     NaN     NaN
3     NaN     NaN
4     NaN     NaN

第 1 行到第 4 行是 NaN。我怎样才能避免这种情况?例如,第 1 行应为 -90 8 (-90=-150*0.6; 8=20*0.4)。

例如,Numpy 可能会广播以匹配维度。

最佳答案

编辑:对于任意维度,尝试使用 values 以类似数组的方式操作数据帧的值:

# element-wise multiplication
frame_score_weighted = frame_score.values*frame_weights.values

# change to pandas dataframe and rename columns
frame_score_weighted = pd.DataFrame(data=frame_score_weighted, columns=['Score1','Score2'])

#Out: 
   Score1  Score2
0    60.0    32.0
1   -90.0     8.0
2   -66.0    28.0
3   108.0    39.6
4    75.0     8.0

只需使用一些额外的索引来确保在进行乘法时将所需的权重提取为标量。

frame_score['Score1'] = frame_score['Score1']*frame_weights['Score1'][0]
frame_score['Score2'] = frame_score['Score2']*frame_weights['Score2'][0]

frame_score
#Out: 
   Score1  Score2
0    60.0    32.0
1   -90.0     8.0
2   -66.0    28.0
3   108.0    39.6
4    75.0     8.0

关于python - 如何在 pandas 中将 n*m DataFrame 与 1*m DataFrame 相乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45421723/

相关文章:

python - 验证 Unicode 名称

python - 64 位 pyodbc 是否可以与 32 位 MS Access 数据库通信?

python - 使用 pandas 中的查询函数返回位于两个列表交集的行

python - 如何更新数据帧值

python - 检查类型 : How to check if something is a RDD or a DataFrame?

python - python中函数的len()

python - 循环遍历列表并在找到第一个字符串时停止

pandas - 如何在 Pandas 时间序列中存储向量?

r - 从 R 中的现有数据框中提取数据(或 reshape )数据框

python - 如何对 Pandas 的多索引进行分组?