[英]Pandas pivot table arrangement no aggregation
我想在沒有聚合的情況下轉動pandas數據幀,而不是垂直呈現數據透視索引列,我想要水平呈現它。 我試過pd.pivot_table
但我沒有得到我想要的。
data = {'year': [2011, 2011, 2012, 2013, 2013],
'A': [10, 21, 20, 10, 39],
'B': [12, 45, 19, 10, 39]}
df = pd.DataFrame(data)
print df
A B year
0 10 12 2011
1 21 45 2011
2 20 19 2012
3 10 10 2013
4 39 39 2013
但我希望:
year 2011 2012 2013
cols A B A B A B
0 10 12 20 19 10 10
1 21 45 NaN NaN 39 39
您可以首先通過創建新的索引列cumcount
,然后stack
與unstack
:
df['g'] = df.groupby('year')['year'].cumcount()
df1 = df.set_index(['g','year']).stack().unstack([1,2])
print (df1)
year 2011 2012 2013
A B A B A B
g
0 10.0 12.0 20.0 19.0 10.0 10.0
1 21.0 45.0 NaN NaN 39.0 39.0
如果需要設置列名,請使用rename_axis
( pandas
0.18.0
new):
df['g'] = df.groupby('year')['year'].cumcount()
df1 = df.set_index(['g','year'])
.stack()
.unstack([1,2])
.rename_axis(None)
.rename_axis(('year','cols'), axis=1)
print (df1)
year 2011 2012 2013
cols A B A B A B
0 10.0 12.0 20.0 19.0 10.0 10.0
1 21.0 45.0 NaN NaN 39.0 39.0
用另一種解決方案pivot
,但你需要交換的第一級和第二級Multiindex
在列swaplevel
,然后排序它通過sort_index
:
df['g'] = df.groupby('year')['year'].cumcount()
df1 = df.pivot(index='g', columns='year')
df1 = df1.swaplevel(0,1, axis=1).sort_index(axis=1)
print (df1)
year 2011 2012 2013
A B A B A B
g
0 10.0 12.0 20.0 19.0 10.0 10.0
1 21.0 45.0 NaN NaN 39.0 39.0
print (df1)
year 2011 2012 2013
A B A B A B
g
0 10.0 12.0 20.0 19.0 10.0 10.0
1 21.0 45.0 NaN NaN 39.0 39.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.