python - 将 MultiIndex Pandas Dataframe 乘以另一个数据帧中的多个标量

标签 python pandas

如何将 MultiIndex 数据框中的列与多个标量(来自另一个数据框)相乘?

对于普通数据帧,它是 fairly straightforward ,但是当它到达多索引数据帧时我感到困惑。有什么建议吗?

虚拟数据:

import pandas as pd
import numpy as np

def mklbl(prefix, n):
    return ["%s%s" % (prefix, i) for i in range(n)]

miindex = pd.MultiIndex.from_product([mklbl('C', 4), mklbl('D', 2)])
micolumns = pd.MultiIndex.from_tuples([('Baseline', 'Electricity'), ('Baseline', 'Gas'), ('Consumption', 'Electricity'), ('Consumption', 'Gas')])
df = pd.DataFrame(np.arange(len(miindex) * len(micolumns))
                        .reshape((len(miindex), len(micolumns))),
                         index=miindex,
                  columns= micolumns)

cost = pd.DataFrame([['Electricity', 0.12],['Gas', 0.03]], columns=['fuel__name', 'cost_per_unit'])

预期输出是虚拟数据乘以电力天然气的相应cost_per_unit(即能源使用成本)

最佳答案

将第一级列映射到值并相乘:

df_res = df*df.columns.get_level_values(1).map(cost.set_index('fuel__name').cost_per_unit)
print(df_res)

         Baseline       Consumption      
      Electricity   Gas Electricity   Gas
C0 D0        0.00  0.03        0.24  0.09
   D1        0.48  0.15        0.72  0.21
C1 D0        0.96  0.27        1.20  0.33
   D1        1.44  0.39        1.68  0.45
C2 D0        1.92  0.51        2.16  0.57
   D1        2.40  0.63        2.64  0.69
C3 D0        2.88  0.75        3.12  0.81
   D1        3.36  0.87        3.60  0.93

如果您只需要乘以特定的子集,那么您可以使用各种方法对 MultiIndex 进行切片,并仅对子集执行操作。

import pandas as pd
df.loc[:, df.columns.get_level_values(1) == 'Electricity']

         Baseline Consumption
      Electricity Electricity
C0 D0           0           2
   D1           4           6
C1 D0           8          10
...

使用pd.IndexSlice也许会更简洁和可读

idx = pd.IndexSlice
df.loc[:, idx[:, 'Electricity']]

         Baseline Consumption
      Electricity Electricity
C0 D0           0           2
   D1           4           6
C1 D0           8          10
...

关于python - 将 MultiIndex Pandas Dataframe 乘以另一个数据帧中的多个标量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54539544/

相关文章:

python - 使用 pandas DataFrame 打开 JSON 文件

python - 使用 Pandas 中其他行的排列生成新行

python - 使用 Pandas 为每个过滤器识别列中最接近的值

python - 如何在 Shell 提示时使 python 脚本按 'enter'

python - 使用 Python2.6 抓取时抓取子字符串

python - 在 Python 中提取序列

python - 在 Pandas 时间序列中每天查询相同的时间值

python - 如何添加两个DataFrame

python - 限制为 django admin 内联显示的条目的查询集

python - 简单的 Python UDP 服务器 : trouble receiving packets from clients other than localhost