pandas pivot_table 保持索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38729856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:43:48  来源:igfitidea点击:

pandas pivot_table keep index

pythonpandaspivotpivot-table

提问by Vincent Claes

i have a dataframe :

我有一个数据框:

   day_bucket  label  numeric_value
0  2011-01-21  birds              4
1  2011-01-22  birds              0
2  2011-01-23  birds              7
3  2011-01-24  birds              3

I want to pivot this dataframe so that i have a column birdswith the values below it.

我想旋转此数据框,以便我有一列birds其下方的值。

pd.pivot_table(df, values='numeric_value', index='day_bucket',columns='label')  

gives:

给出:

label       birds
day_bucket             
2011-01-21  4
2011-01-22  0
2011-01-23  7
2011-01-24  3

what should i do the keep the index? The result will look like:

我该怎么做才能保持索引?结果将如下所示:

    day_bucket birds    
0   2011-01-21  4
1   2011-01-22  0
2   2011-01-23  7
3   2011-01-24  3 

回答by piRSquared

set_indexwith append

set_indexappend

df.set_index(['day_bucket', 'label'], append=True) \
  .rename_axis([None, None, None]).squeeze().unstack()

enter image description here

在此处输入图片说明

回答by Vincent Claes

In the meantime, I also came up with a result

与此同时,我也想出了一个结果

pd.pivot_table(df, values='numeric_value', 
                   index=[df.index.values,'day_bucket'],
                   ,columns='label').reset_index('day_bucket')

label  day_bucket  mortality_birds
0      2011-01-21                4
1      2011-01-22                0
2      2011-01-23                7
3      2011-01-24                3

回答by Sean.H

just for supplement: this works fine, we can get:

仅供补充:这很好用,我们可以得到:

pt2 = pt.rename_axis(None, axis=1).reset_index()
print(pt2)

   day_bucket  birds
0  2011-01-21      4
1  2011-01-22      0
2  2011-01-23      7
3  2011-01-24      3


the dataframe used for it is:

用于它的数据框是:

df = pd.DataFrame({'day_bucket': ['2011-01-21', '2011-01-22', '2011-01-23', '2011-01-24'],
                   'label': ['birds', 'birds', 'birds', 'birds'],
                   'num_value': [4, 0, 7, 3]})

pt = pd.pivot_table(df,
                    values='num_value',
                    index='day_bucket',
                    columns='label',
                    aggfunc=np.sum)
print(pt, '\n')

label       birds
day_bucket       
2011-01-21      4
2011-01-22      0
2011-01-23      7
2011-01-24      3