我有一个带有列名的多级索引
我有一个看起来像数据表的东西。
DataFrame
。我想要轻松地调整列的顺序,以使其与用户指定的顺序匹配。由于这是在管道中进行的,我无法在创建时正确排序,也不能使用推荐的解决方案。我有一个看起来像数据表的东西。
Experiment BASE IWWGCW IWWGDW
Lead Time 24 48 24 48 24 48
2010-11-27 12:00:00 0.997 0.991 0.998 0.990 0.998 0.990
2010-11-28 12:00:00 0.998 0.987 0.997 0.990 0.997 0.990
2010-11-29 12:00:00 0.997 0.992 0.997 0.992 0.997 0.992
2010-11-30 12:00:00 0.997 0.987 0.997 0.987 0.997 0.987
2010-12-01 12:00:00 0.996 0.986 0.996 0.986 0.996 0.986
我希望能够输入一个列表,如['IWWGCW', 'IWWGDW', 'BASE']
,并重新排序为:
Experiment IWWGCW IWWGDW BASE
Lead Time 24 48 24 48 24 48
2010-11-27 12:00:00 0.998 0.990 0.998 0.990 0.997 0.991
2010-11-28 12:00:00 0.997 0.990 0.997 0.990 0.998 0.987
2010-11-29 12:00:00 0.997 0.992 0.997 0.992 0.997 0.992
2010-11-30 12:00:00 0.997 0.987 0.997 0.987 0.997 0.987
2010-12-01 12:00:00 0.996 0.986 0.996 0.986 0.996 0.986
需要注意的是,我并不总是知道“实验”会处于哪个级别。我尝试过(其中df
是上面显示的多级索引框架)。
df2 = df.reindex_axis(['IWWGCW', 'IWWGDW', 'BASE'], axis=1, level='Experiment')
但似乎并没有起作用 - 虽然成功完成,但返回的DataFrame未改变其列顺序。
我的解决方法是创建一个函数:
def reorder_columns(frame, column_name, new_order):
"""Shuffle the specified columns of the frame to match new_order."""
index_level = frame.columns.names.index(column_name)
new_position = lambda t: new_order.index(t[index_level])
new_index = sorted(frame.columns, key=new_position)
new_frame = frame.reindex_axis(new_index, axis=1)
return new_frame
我希望能够更简单地实现这个功能:reorder_columns(df, 'Experiment', ['IWWGCW', 'IWWGDW', 'BASE'])
。虽然目前这种方式可以达到预期效果,但感觉多做了一些工作。是否有更简便的方法呢?