【问题标题】:Grouped, binned, cumulative sum in PandasPandas 中的分组、分箱、累积总和
【发布时间】:2018-05-30 14:09:57
【问题描述】:

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

【问题讨论】:

    标签: python excel numpy countif pandas-groupby


    【解决方案1】:
    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
    

    【讨论】:

      猜你喜欢
      • 2015-09-11
      • 2021-06-15
      • 2018-09-02
      • 2023-03-16
      • 2014-04-12
      • 2014-07-13
      • 2019-02-15
      • 2019-05-04
      • 2019-12-01
      相关资源
      最近更新 更多