python - 就地修改多索引 pandas 数据框乘以标量

标签 python pandas

我有一个类似于

的多索引数据框
                      value       identifier

EA    2007-01-01      0.33            55
      2007-01-01      0.73            56
      2007-01-01      0.51            57
      2007-02-01      0.13            55
      2007-02-01      0.23            57
      2007-03-01      0.82            55
      2007-03-01      0.88            56
      2007-03-01      0.19            57
      2008-01-01      0.36            55
      2008-01-01      0.26            57
      2008-02-01      0.17            55
      2008-02-01      0.17            56
      2008-02-01      0.57            57
      2008-03-01      0.75            55
      2008-03-01      0.45            56
EB    2007-01-01      0.13            55
      2007-01-01      0.74            56
      2007-01-01      0.56            57
      2007-02-01      0.93            55
      2007-02-01      0.23            57
      2007-03-01      0.82            55
      2007-03-01      0.38            56
      2007-03-01      0.19            57
      2008-01-01      0.46            55
      2008-01-01      0.26            57
      2008-02-01      0.67            55
      2008-02-01      0.98            56
      2008-02-01      0.11            57
      2008-03-01      0.75            55
      2008-03-01      0.22            56

和一个带有值的字典

weights = {"EA":0.1, "EB":0.7}

我正在尝试将所有值乘以权重。第一个显而易见的方法是

for key, weight in weigths.items():
    df[key]['value'] = df[key]['value'] * weight

但这给出了警告:

 SettingWithCopyWarning: 
 A value is trying to be set on a copy of a slice from a DataFrame.
 Try using .loc[row_indexer,col_indexer] = value instead

所以我尝试了这个:

for key, weight in weigths.items():
    df.loc[key,'value'] = df.loc[key,'value'] * weight

但随后它找不到列value。这种形式有效,但它给出了相同的警告:

for key, weight in weigths.items():
    df.loc[key]['value'] = df.loc[key]['value'] * weight

基于documentation ,我理解此警告可能相关的原因,但是如何才能将这些值相乘呢?

最佳答案

这不是您直接提出的问题,但我会对此问题采取不同的方法,该方法应该运行得更快:

df['wt'] = df['index'].map(weights)

df

   index        date  value  identifier   wt
0     EA  2007-01-01   0.33          55  0.1
1     EA  2007-01-01   0.73          56  0.1
2     EA  2007-01-01   0.51          57  0.1

...

15    EB  2007-01-01   0.13          55  0.7
16    EB  2007-01-01   0.74          56  0.7
17    EB  2007-01-01   0.56          57  0.7

我假设 EA/EB 位于名为“index”的列中,因此您可能必须在执行此操作之前重置_index。

从那里开始,这只是常规乘法。

df[['value','identifier']].mul(df['wt'],axis=0)

关于python - 就地修改多索引 pandas 数据框乘以标量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30058275/

相关文章:

python - Scrapy 中的项目缓存

python - 如何在 Excel/csv 中保存数据帧值

python - 使用 pandas 数据框中使用多列的多个自定义函数聚合多列的有效方法是什么?

python - keras LSTM 预测不佳

python - ValueError:需要至少一个数组来连接

python - 随着主窗口大小的调整而调整 QDialog 的大小

python - Pandas 中的条件虚拟变量

python - 精确但没有尾随 0 的圆 Pandas 列

python - 数据框未在 Pycharm 中显示

python非线性最小二乘拟合