Pandas:用两个不同的维度创建透视表?

2024-09-28 13:23:36 发布

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

我是熊猫新手。我有一个赞助商和公司参加考试的数据框:

import pandas pd

df = pd.DataFrame({
  'sponsor': ['A71991', 'A71991', 'A71991', 'A81001', 'A81001'],
  'sponsor_class': ['Industry', 'Industry', 'Industry', 'NIH', 'NIH'],
  'year': [2012, 2013, 2013, 2012, 2013],
  'passed': [True, False, True, True, True],
})

现在,我要输出一个CSV文件,其中包含每个赞助商及其类的行,以及按年度列出的通过率和总费率的列:

^{pr2}$

如何从df到这个经过重构的数据帧?我想我需要按sponsorsponsor_class分组,然后将总数和{}是{}的计数按年旋转,然后将这些列展平。(我知道我以pd.write_csv(mydf)结尾。)

我试着从这个开始:

df_g = df.groupby(['sponsor', 'sponsor_class', 'year', 'passed'])

但这给了我一个空的数据帧。在

我想我需要一个透视表来透视这一年并通过状态。。。但我不知道从哪里开始。在

更新:获取某个地方:

df_g = df_completed.pivot_table(index=['lead_sponsor', 'lead_sponsor_class'], 
                                columns='year', 
                                aggfunc=len, fill_value=0)
df_g[['passed']]

现在我需要解决(1)如何获得所有行的计数以及passed,以及(2)如何为CSV文件取消列嵌套。在


Tags: 文件csv数据truedfyearclasspd
2条回答
# set index to prep for unstack
df1 = df.set_index(['sponsor', 'sponsor_class', 'year']).astype(int)

# groupby all the stuff in the index
gb = df1.groupby(level=[0, 1, 2]).passed

# use agg to get sum and count    
# swaplevel and sort_index to get stuff sorted out
df2 = gb.agg({'passed': 'sum', 'total': 'count'}) \
          .unstack().swaplevel(0, 1, 1).sort_index(1)

# collapse multiindex into index
df2.columns = df2.columns.to_series().apply(lambda x: '{}_{}'.format(*x))

print df2.reset_index().to_csv(index=None)


sponsor,sponsor_class,2012_passed,2012_total,2013_passed,2013_total
A71991,Industry,1,1,1,2
A81001,NIH,1,1,1,1

我可以通过几个步骤了解如何做到这一点:

import numpy as np, pandas as pd
df['total'] = df['passed'].astype(int)
ldf = pd.pivot_table(df,index=['sponsor','sponsor_class'],columns='year',
                     values=['total'],aggfunc=len) # total counts
rdf = pd.pivot_table(df,index=['sponsor','sponsor_class'],columns='year',
                     values=['total'],aggfunc=np.sum) # number passed 
cdf = pd.concat([ldf,rdf],axis=1) # combine horizontally
cdf.columns = cdf.columns.get_level_values(0) # flatten index
cdf.reset_index(inplace=True)
columns = ['sponsor','sponsor_class']
yrs = sorted(df['year'].unique())
columns.extend(['{}_total'.format(yr) for yr in yrs])
columns.extend(['{}_passed'.format(yr) for yr in yrs])
cdf.columns = columns

结果:

^{pr2}$

最后:

cdf.to_csv('/path/to/file.csv',index=False)

相关问题 更多 >

    热门问题