爱不是伤害吧 关注:13贴子:661
  • 0回复贴,共1

近期用pandas的一些备忘

取消只看楼主收藏回复

multi-index的多层级分类汇总
有三种方法:
方法一:groupby
示例如下,比如,需要在,大类、细分1、细分2、部门,四个层级,求subtotal:
groupby1= gongshi_jichu['分摊工时'].groupby([gongshi_jichu['大类'],gongshi_jichu['细分1'],gongshi_jichu['细分2'],gongshi_jichu['填报dept2'],gongshi_jichu['月']]).agg(np.sum).unstack().fillna(0)
groupby2 = groupby1.groupby(level=[0,1]).sum()
groupby2.index = pd.MultiIndex.from_arrays([groupby2.index.get_level_values(0),groupby2.index.get_level_values(1) + ' ',len(groupby2) * ['']])
groupby3 = groupby1.groupby(level=[0]).sum()
groupby3.index = pd.MultiIndex.from_arrays([groupby3.index.get_level_values(0) + ' ',
len(groupby3) * [''],
len(groupby3) * ['']])
groupby4 = pd.concat([groupby1,groupby2,groupby3]).sort_index()
为了解决导出的excel中的index合并为字符元组的问题,
groupby4.to_excel('groupby4.xlsx',sheet_name='groupby4',freeze_panes=[1,0],merge_cells=False)
groupby4_reread=pd.read_excel('groupby4.xlsx')
groupby4_reread['index']=list(groupby4_reread.index)
groupby4_reread['大类']=groupby4_reread['index'].apply(lambda x:get_list_4(x)[0])
groupby4_reread['细分1']=groupby4_reread['index'].apply(lambda x:get_list_4(x)[1])
groupby4_reread['细分2']=groupby4_reread['index'].apply(lambda x:get_list_4(x)[2])
groupby4_reread['二级部门']=groupby4_reread['index'].apply(lambda x:get_list_4(x)[3])
groupby4_reread_2=groupby4_reread[['大类', '细分1', '细分2', '二级部门',1, 2, 3]]
groupby4_reread_2.to_excel('分类汇总结论文件.xlsx',sheet_name='groupby5',freeze_panes=[1,0],merge_cells=False)
groupby加上concat语法实现
groupby_1_v2= gongshi_jichu['分摊工时'].groupby([gongshi_jichu['大类'],gongshi_jichu['细分1'],gongshi_jichu['细分2'],gongshi_jichu['填报dept2'],gongshi_jichu['填报dept3'],gongshi_jichu['月']]).agg(np.sum).unstack().fillna(0)
subtotal_list_2=['大类','细分1','细分2','填报dept2','填报dept3']
concat8 =pd.concat([
groupby1.assign(
**{x: 'total' for x in subtotal_list_2[i:]}
).groupby(subtotal_list_2).sum() for i in range(4)
]).sort_index()
concat9 = pd.concat([groupby_1_v2,concat8]).sort_index()
concat9.to_excel('分类汇总结果文件.xlsx',sheet_name='concat9',freeze_panes=[1,0],merge_cells=False)
通过pivot_table的参数margin=True,然后做stack
fentanleibie_bumen_week_subtotal_pre = pd.pivot_table(gongshi_jichu,index=['大类','细分1','细分2',],columns=['月','填报dept2'],values=['分摊工时'],aggfunc=[np.sum],fill_value=0,margins=1,margins_name='分类汇总')
fentanleibie_bumen_week_stacked = fentanleibie_bumen_week_subtotal_pre.stack('填报dept2')
fentanleibie_bumen_week_stacked.to_excel('分类汇总结果文件.xlsx',sheet_name='各分摊类型二级部门_2',freeze_panes=[1,0],merge_cells=False)
使用apply(lambda x: func(x))函数为dataframe新增新列
这个的局限是,只能对一列派生出新列;如果需要综合多个列的值、来决定新列的值,可以把多个列做字符串串接起来、拼接为一个列后、针对拼接后的列,来派生新列。
释放本地内存的方法
办法:
import gc (garbage collector)
del a
gc.collect()


1楼2018-03-13 14:17回复