一次具有多个列的Pandas数据透视表 [英] Pandas pivot table with multiple columns at once
问题描述
我想知道pandas.pivot_table
是否可以一次接受两列并分别处理而不是按层次处理.
I wonder if pandas.pivot_table
can accept two columns at once and process them separately instead of hierarchically.
说我有以下数据框:
id date day val
101 11/1/1 1 2.1
101 11/1/2 2 2.2
101 11/1/3 3 2.3
102 11/1/2 1 3.1
102 11/1/3 2 3.2
102 11/1/4 3 3.3
我希望结果是这样的:
date day
id 11/1/1 11/1/2 11/1/3 11/1/4 1 2 3
101 2.1 2.2 2.3 NaN 2.1 2.2 2.3
102 NaN 3.1 3.2 3.3 3.1 3.2 3.3
当我执行df.pivot_table(index='id', columns=['date','day'], values='val')
时,它将把date
和day
集成到不是我想要的层次结构中.当然,我可以分别对date
和day
进行两次并连接结果,但是有一次更方便的方法吗?
When I do df.pivot_table(index='id', columns=['date','day'], values='val')
, it will integrate date
and day
into a hierarchy which is not what I want. Of course I can do twice with date
and day
respectively and concatenate the results, but is there a more convenient way to do so at once?
推荐答案
您可以进行2次pivot
调用并concat
启用结果.
You can make 2 pivot
calls and concat
enate the result.
i = df.pivot('id', 'date', 'val')
j = df.pivot('id', 'day', 'val')
pd.concat([i, j], 1, keys=['date', 'day'])
date day
11/1/1 11/1/2 11/1/3 11/1/4 1 2 3
id
101 2.1 2.2 2.3 NaN 2.1 2.2 2.3
102 NaN 3.1 3.2 3.3 3.1 3.2 3.3
作为单个衬纸-
As a single liner -
c = ['date', 'day'] # add more cols as needed
pd.concat([df.pivot('id', x, 'val') for x in c], axis=1, keys=c)
date day
11/1/1 11/1/2 11/1/3 11/1/4 1 2 3
id
101 2.1 2.2 2.3 NaN 2.1 2.2 2.3
102 NaN 3.1 3.2 3.3 3.1 3.2 3.3
这篇关于一次具有多个列的Pandas数据透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!