python - pandas 中多索引数据帧的累积百分比

标签 python pandas

我想计算 pandas 中多索引数据帧的累积百分比,但无法让它工作。

import pandas as pd

to_df = {'domain': {(12, 12): 2, (14, 14): 1, (15, 15): 2, (15, 17): 2, (17, 17): 1},
 'time': {(12, 12): 1, (14, 14): 1, (15, 15): 2, (15, 17): 1, (17, 17): 1},
 'weight': {(12, 12): 3,
  (14, 14): 4,
  (15, 15): 1,
  (15, 17): 2,
  (17, 17): 5}}

df = pd.DataFrame.from_dict(to_df)

       domain  time  weight
12 12       2     1       3
14 14       1     1       4
15 15       2     2       1
   17       2     1       2
17 17       1     1       5


df = df.groupby(['time', 'domain']).apply(
 pd.DataFrame.sort_values, 'weight', ascending=True)

cumsum() 按预期工作

df["cum_sum_time_domain"] = df.groupby(['time', 'domain'])['weight'].cumsum()



               domain  time  weight  cum_sum_time_domain
time domain                                                 
1    1      14 14       1     1       4                    4
            17 17       1     1       5                    9
     2      15 17       2     1       2                    2
            12 12       2     1       3                    5
2    2      15 15       2     2       1                    1

运行命令本身确实有效

df.groupby(['time', 'domain']).weight.sum()
df.groupby(['time', 'domain'])['weight'].sum()

然而,这两个赋值突然产生“NaN”

df["sum_time_domain"] = df.groupby(['time', 'domain']).weight.sum()
df
df["sum_time_domain"] = df.groupby(['time', 'domain'])['weight'].sum()
df

将两者结合起来会出现错误:“未实现在多索引上与多于一层重叠的合并”

df["cum_perc_time_domain"] = 100 * df.groupby(['time', 'domain'])['weight'].cumsum() / df.groupby(
 ['time', 'domain'])['weight'].sum()

最佳答案

我认为你需要transform总和。另外,对于 groupby 排序也是不必要的,仅使用 sort_values :

df = df.sort_values(['time','domain','weight'])

print (df.groupby(['time', 'domain']).weight.transform('sum'))
14  14    9
17  17    9
15  17    5
12  12    5
15  15    1
Name: weight, dtype: int64

df["cum_perc_time_domain"] = 100 * df.groupby(['time', 'domain'])['weight'].cumsum() / 
                                   df.groupby(['time', 'domain']).weight.transform('sum')
print (df)
       domain  time  weight  cum_perc_time_domain
14 14       1     1       4             44.444444
17 17       1     1       5            100.000000
15 17       2     1       2             40.000000
12 12       2     1       3            100.000000
15 15       2     2       1            100.000000

关于python - pandas 中多索引数据帧的累积百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41057992/

相关文章:

python - django如何隐藏特定表单字段并循环数据输入

python - 当在 pyqt4 中按下修改键时,将所有键盘命令自动传输到嵌入式 mplayer 实例

python - Pandas 映射 2 dfs

python - 如何在 python 中用数据框中的随机整数替换 0?

python - 将 pandas "Series of pair arrays"转换为 "two-column DataFrame"?

python - 如何测试键是否在另一个字典中的字典中?

python - python 中的 mininet dpctl mod-port

python-3.x - Pandas Indexing-View-Versus-Copy

python - 如何将单列 Pandas DataFrame 转换为 Series

python - 我如何将一个 DataFrame 与其他 DataFrame 的列进行比较?