pandas pivot_table保持索引

时间:2016-08-02 20:26:50

标签: python pandas pivot pivot-table

我有一个数据框:

   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

我想转动此数据框,以便我有一个列birds,其值低于它。

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

给出:

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

我该怎么做才能保留索引?结果如下:

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

3 个答案:

答案 0 :(得分:5)

带有set_index

append

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

enter image description here

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

仅作为补充: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 可以正常工作。

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

我们可以获得:

if (isset($_POST['submit']))
{
    // do something here
} 
elseif (isset($_POST['cancel']))
{
    // redirect here
}