我正在尝试计算累积总和,然后将此累积总和的每一列除以另一个数据框列。请参阅下面的代码。
import pandas as pd
import numpy as np
def cum_sums(input_df):
bin_values = np.arange(0, 72, 24)
group_names = np.arange(0, 48, 24)
input_df['categories'] = pd.cut(input_df['time'], bin_values, labels=group_names)
category_sum = input_df.groupby(['area', 'categories'])['categories'].size()
cum_sum = category_sum.groupby(level=[0]).cumsum().reset_index(name='cum_sum')
# pivot to get right format
cum_sum_flipped = cum_sum.pivot(index='area', columns='categories', values='cum_sum')
# and then add back in any missing categories
cum_sum_flipped = cum_sum_flipped.reindex(columns=group_names).ffill(axis=1).replace('Nan', 0, regex=True)
return cum_sum_flipped
data1 = {'area': ['a', 'b', 'c', 'a', 'b'],
'time': [7, 11, 25, 27, 34]}
data2 = {'area': ['a', 'b', 'c'],
"count": [2, 2, 3]}
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)
df = cum_sums(df1)
print(df)
print(df2['count'])
df = df.div(df2['count'], axis='columns')
print(df)
这会产生:
0 1 2 24
area
a 0.5 NaN NaN NaN
b 0.5 NaN NaN NaN
c 0.0 NaN NaN NaN
我期待的地方:
0 24
area
a 0.5 1.0
b 0.5 1.0
c 0.0 0.33333
我怀疑通过添加缺少的类别,我正在改变div的工作原理,但这是猜测。为了得到我期望的答案,我错过了什么?
答案 0 :(得分:3)
如果df2
的长度与df1
相同且上次更改df2
,则可以按df1
的索引设置axis='index'
的索引:
df2.index = df.index
df = df.div(df2['count'], axis='index')
print(df)
categories 0 24
area
a 0.5 1.000000
b 0.5 1.000000
c 0.0 0.333333