我试图用一个序列来乘一个DataFrame,其中DataFrame具有与Series完全相同的索引,尽管具有重复的索引值。所期望的结果是,根据索引的值,DataFrame中的每一行被乘以序列中的相应值。
将具有重复索引值的系列相乘,效果非常好:
import pandas as pd
weights = pd.Series([10, 100], [0, 1])
s = pd.Series([1, 2, 3, 4], [0, 0, 1, 1])
s.mul(weights)
产生预期结果:
0 10
0 20
1 300
1 400
然而,将DataFrame与重复的索引值相乘会产生一个ValueError:无法从重复轴重新索引
df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [-1, -2, -3, -4]}, [0, 0, 1, 1])
df.mul(weights, axis=0)
...
ValueError: cannot reindex from a duplicate axis
如何取得以下结果?
a b
0 10 -10
0 20 -20
1 300 -300
1 400 -400
编辑:
一种选择是首先重新编制权重系列的索引:
df.mul(weights.reindex(df.index, method='ffill'), axis=0)
发布于 2017-02-26 18:23:43
如何使用apply
方法使数据帧逐列相乘?
df.apply(lambda col: col.mul(weights))
# a b
#0 10 -10
#0 20 -20
#1 300 -300
#1 400 -400
https://stackoverflow.com/questions/42472333
复制相似问题