我正在从excel Countifs / Sum过渡到Pandas。在Pandas中,我想对某些输入数据进行分组,分箱,累加求和,然后我将其作为输出表写入csv。
我的输入表是每个项目发生的项目的时间戳列表,如:
import pandas as pd
df_in = pd.DataFrame({ 'Date' :[pd.Timestamp('20130101'),pd.Timestamp('20140101'),pd.Timestamp('20150101'),pd.Timestamp('20160101'),pd.Timestamp('20160101'),pd.Timestamp('20160101')],
'Type' : ['item1','item2','item2','item1','item1','item1'],
'Proj' : ['PJ1','PJ1','PJ1','PJ1','PJ2','PJ2']})
#giving
Proj Date Type
PJ1 2013-01-01 item1
PJ1 2014-01-01 item2
PJ1 2015-01-01 item2
PJ1 2016-01-01 item1
PJ2 2016-01-01 item1
PJ2 2016-01-01 item1
我想在一系列用户定义的时间窗口中对每个项目的每个项目类型进行累计求和(最后我想要在一个时间集上实现每个项目的累计项目数 - 月,季度,年等) 。我的输出(分箱到结束日期)应该看起来像
Proj Date_ item1 item2
PJ1 2014-01-01 1.0 1.0
PJ1 2016-01-01 2.0 2.0
PJ2 2014-01-01 0.0 0.0
PJ2 2016-01-01 2.0 0.0
此代码有效,但看起来很笨拙,需要循环。有没有更好的方法来实现产出?也许是矢量化的东西?此外,我总是希望保留输出箱,即使它们中有空数据 - 以后需要它们来进行一致的绘图。
#prepare output table
df_out = pd.DataFrame({
'Date_' : [],
'Proj' : [],
'item1' : [],
'item2' : []})
#my time bins
bins = [pd.Timestamp('20121229'),pd.Timestamp('20140101'),pd.Timestamp('20160101')]
#group and bin data in a dataframe
groups = df_in.groupby(['Proj',pd.cut(df_in.Date, bins),'Type'])
allData = groups.count().unstack()
#list of projects in data
proj_list = list(set(df_in['Proj']))
#build output table by looping per project
for p in proj_list:
#cumulative sum of items achieved per project per bin
ProjData = allData.loc[p].fillna(0).cumsum()
#output should appear binned to the end date
ProjData=ProjData['Date'][:]
ProjData['Date_']=pd.IntervalIndex(ProjData.index.get_level_values('Date')).right
#include row wise project reference
ProjData['Proj']=p
#collapse the multi-dimensional dataframe for outputting
ProjData.reset_index(level=0, inplace=True)
ProjData.reset_index(level=0, inplace=True)
#build output table for export
df_out = df_out.append(ProjData[['Date_','Proj','item1','item2']])
答案 0 :(得分:0)
import itertools
>>> index = list(itertools.product(df['Date'].unique(), df['Proj'].unique()))
>>> df.sort_values(['Proj', 'Date'], inplace=True)
>>> df['CumCount'] = df.groupby(['Proj', 'Type']).cumcount() + 1
>>> df.drop_duplicates(['Date', 'Type', 'Proj'], keep='last', inplace=True)
>>> df = df.pivot_table(values='CumCount', index=['Date', 'Proj'], columns='Type')
>>> df.reindex(index).unstack('Proj').fillna(method='ffill').fillna(0).stack()
Type item1 item2
Date Proj
2013-01-01 PJ1 1.0 0.0
PJ2 0.0 0.0
2014-01-01 PJ1 1.0 1.0
PJ2 0.0 0.0
2015-01-01 PJ1 1.0 2.0
PJ2 0.0 0.0
2016-01-01 PJ1 2.0 2.0
PJ2 2.0 0.0