python - 如何对pandas多级列进行设置和分组?

标签 python pandas dataframe pivot pivot-table

我有一个形状如下的数据框:

   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  ...

是否有更简洁的方法来执行此操作,以便我可以获得我想要的格式?

最佳答案

一个选项是meltset_indexunstack:

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

meltpivot_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/

相关文章:

python - HTTPResponse 对象没有属性 json

python - 元数据收集

python - 合并 'left' ,但尽可能覆盖 'right' 值

python - 仅将数字的字符串表示形式转换为 Pandas 中的数字

python - 在新的更大图像上复制图像

python - 项目在列表中的位置

python - 如何 reshape (pivot_wider和pivot_longer)pandas DataFrame

python - Pandas 尽可能压平行

iterator - 使用 `@transform` 在 Julia 中转换 DataFrame

python - 您不认为从系列列表创建 DataFrame 很奇怪吗?