大Pandas分组、分仓、累计和

2024-09-28 05:17:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从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

我希望在一系列用户定义的时间窗口内,对每个项目的每种项目类型进行累计和(最后,我希望得到每个项目在一个时间集中实现的项目的累计数量-月、季、年等)。我的输出(截止到结束日期)应该是

^{pr2}$

这段代码可以工作,但看起来很笨拙,需要循环。有没有更好的方法来实现产出?可能是矢量化的?此外,我总是希望保留输出箱,即使其中有空数据-它们是以后需要的,以便进行一致的绘图。在

#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']])

Tags: 项目indfoutputdate时间timestamplist
1条回答
网友
1楼 · 发布于 2024-09-28 05:17:00
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

相关问题 更多 >

    热门问题