Pandas:将数据透视表列重新排序为任意ord

2024-09-23 22:21:01 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个透视表,如下所示:

                             completed_olns                  total_completed_olns
work_type                             A     B          C                     
employee                                                                     
Employee1                            94  1163          1                 1258
Employee2                           168   770          4                  942
Employee3                           173   746          8                  927

如何将A、B、C列重新排列为任意顺序,如B、A、C?你知道吗

这些数据是从数据库输出的,并通过带有pd.read_csv()的csv读入

我试过pivot.sort_index(level=1, axis=1, ascending=False),这让我更接近我需要的东西。你知道吗

我也试过pivot = pivot[['B', 'A', 'C']],这给了我:

KeyError: "['B', 'A', 'C'] not in index"

这是我发现的两个最常见的建议。你知道吗


Tags: csv数据数据库index顺序typeemployeework
1条回答
网友
1楼 · 发布于 2024-09-23 22:21:01

.reindexlevel参数一起使用

样本数据

import pandas as pd
import numpy as np

df = pd.DataFrame(data = np.random.randint(1,10,(3,6)))
df.columns = pd.MultiIndex.from_product([['collected', 'total_collected'], ['A','B','C']])
#  collected       total_collected      
#          A  B  C               A  B  C
#0         2  6  9               9  6  6
#1         5  4  4               5  2  6
#2         8  9  3               9  2  7

代码

df.reindex(axis=1, level=1, labels=['B', 'A', 'C'])
#  collected       total_collected      
#          B  A  C               B  A  C
#0         6  2  9               6  9  6
#1         4  5  4               2  5  6
#2         9  8  3               2  9  7

如果组缺少标签或标签不存在,则不会插入所有NaN

df.iloc[:, :-1].reindex(axis=1, level=1, labels=['B', 'A', 'C', 'D'])
#  collected       total_collected   
#          B  A  C               B  A
#0         6  2  9               6  9
#1         4  5  4               2  5
#2         9  8  3               2  9

相关问题 更多 >