Vin*_*aes 3 python pivot pivot-table pandas
我有一个数据帧:
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
Run Code Online (Sandbox Code Playgroud)
我想透过这个数据帧,以便我有一个列birds低于它的列.
pd.pivot_table(df, values='numeric_value', index='day_bucket',columns='label')
Run Code Online (Sandbox Code Playgroud)
得到:
label birds
day_bucket
2011-01-21 4
2011-01-22 0
2011-01-23 7
2011-01-24 3
Run Code Online (Sandbox Code Playgroud)
我应该怎么做保持索引?结果如下:
day_bucket birds
0 2011-01-21 4
1 2011-01-22 0
2 2011-01-23 7
3 2011-01-24 3
Run Code Online (Sandbox Code Playgroud)
与此同时,我也得出了一个结果
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
Run Code Online (Sandbox Code Playgroud)
set_index 同 append
df.set_index(['day_bucket', 'label'], append=True) \
.rename_axis([None, None, None]).squeeze().unstack()
Run Code Online (Sandbox Code Playgroud)