我有一个dataframe,它的列和行都有重复的索引名和有序的SUScript。我想对它们进行重新排序,以便它们按照我指定的特定顺序进行排序。我手动制作了一个简单的示例,如下所示。此代码将生成df,这是具有重复列和行的数据帧。我想使用列向量order,这样我的新数据帧df_new将具有列和行,这些列和行将遵循order指定的顺序(而suscript编号的顺序是递增的)
df = pd.DataFrame({0: [11, 3, 10, 9, 6, 9],
1: [12, 4, 11, 8, 5, 8],
2: [13, 5, 12, 7, 4, 7],
3: [14, 6, 13, 6, 3, 6],
4: [15, 7, 14, 5, 2, 5],
5: [16, 8, 15, 4, 1, 4]})
df = df.rename({0:"apple1", 1:"apple2",2:"banana1",3:"banana2",4:"pear1",5:"pear2"}, axis='columns')
df = df.rename({0:"apple1", 1:"apple2",2:"banana1",3:"banana2",4:"pear1",5:"pear2"}, axis='index')
order = ["banana", "pear", "apple" ]
df_new = pd.DataFrame({2: [12, 7, 4, 7, 13, 5],
3: [13, 6, 3, 6, 14, 6],
4: [14, 5, 2, 5, 15, 7],
5: [15, 4, 1, 4, 16, 8],
0: [10, 9, 6, 9, 11, 3],
1: [11, 8, 5, 8, 12, 4]})
df_new = df_new.rename({0:"apple1", 1:"apple2",2:"banana1",3:"banana2",4:"pear1",5:"pear2"}, axis='columns')
df_new = df_new.rename({0:"apple1", 1:"apple2",2:"banana1",3:"banana2",4:"pear1",5:"pear2"}, axis='index')
df
df_new
我发布了所需的结果图像(我不确定如何将上述代码的输出放在这个问题中),如下所示。谁能给我一个通用的方法来重新排序这些重复的列和行使用特定的顺序(以及相应的单元格?非常感谢
我的做法是:
使用^{} 创建名称为的多索引:
然后在索引和带有} level=0:
order
的列上^{然后用^{} 折叠多索引:
完整代码:
(可选)将级别1转换为int并使用^{} 进行数字排序:
相关问题 更多 >
编程相关推荐