我有一个形状如下的数据框:
PX_LAST PX_OPEN PX_CLOSE ticker source timestamp
0 1 2 3 A LSE 20180101
1 4 5 6 A LSE 20180102
1 7 8 9 B LSE 20180101
1 10 11 12 B LSE 20180102
....
我想将其按摩为以下格式:
A B
LSE LSE
PX_LAST, PX_CLOSE, PX_OPEN PX_LAST, PX_CLOSE, PX_OPEN
timestamp
20180101 1 2 3 7 8 9
20180102 4 5 6 10 11 12
....
我尝试首先使用 set_index
将代码和源列设置为行索引,然后使用 unstack
将它们推到列轴上,这似乎确实有效
df.set_index(['timestamp', 'ticker', 'source'])
.unstack(level=[1,2])
.swaplevel(0,1,axis=1)
.swaplevel(1,2,axis=1)
这确实有效,但有两个问题:1)它非常冗长,我们需要执行所有交换级别调用才能使列变成正确的形状。 2)它似乎没有进行我希望的分组,即我得到的结果是这样的:
LSE LSE LSE LSE ...
PX_LAST PX_LAST PX_CLOSE PX_CLOSE ...
timestamp
20180101 1 7 2 8 ...
20180102 4 8 5 11 ...
是否有更简洁的方法来执行此操作,以便我可以获得我想要的格式?
最佳答案
一个选项是melt
、set_index
和unstack
:
u = df.melt(['ticker', 'source', 'timestamp'])
(u.set_index(u.columns.difference({'value'}).tolist())['value']
.unstack([1, 0, -1])
.sort_index(axis=1))
ticker A B
source LSE LSE
variable PX_CLOSE PX_LAST PX_OPEN PX_CLOSE PX_LAST PX_OPEN
timestamp
20180101 3 1 2 9 7 8
20180102 6 4 5 12 10 11
或melt
和pivot_table
:
u = df.melt(['ticker', 'source', 'timestamp'])
u.pivot_table(index='timestamp',
columns=['ticker','source','variable'],
values='value')
ticker A B
source LSE LSE
variable PX_CLOSE PX_LAST PX_OPEN PX_CLOSE PX_LAST PX_OPEN
timestamp
20180101 3 1 2 9 7 8
20180102 6 4 5 12 10 11
关于python - 如何对pandas多级列进行设置和分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54171216/