大熊猫中多索引数据帧的累积百分比

时间:2016-12-09 10:13:57

标签: 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()
然而,这两项任务突然产生了NaNs'

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()

1 个答案:

答案 0 :(得分:1)

我认为您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