如何重新排列/重新排序(不一定排序)pandas 数据帧索引?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47841373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:55:02  来源:igfitidea点击:

How do I rearrange/reorder (not necessarily sort) a pandas dataframe index?

pythonpandasdataframe

提问by ralphqq

How do I rearrange/reorder (not necessarily sort) a pandas dataframe index?

如何重新排列/重新排序(不一定排序)pandas 数据帧索引?

I have the following dataframe:

我有以下数据框:

df = pd.DataFrame({'A': [1, 2, 3, 4, 5, 6, 7],
                   'B': [0, 1, 0, 2, 1, 7, 1]},
                  index=['Sat', 'Tue', 'Sun', 'Fri',
                         'Wed', 'Mon', 'Thu'])

which gives:

这使:

     A  B
Sat  1  0
Tue  2  1
Sun  3  0
Fri  4  2
Wed  5  1
Mon  6  7
Thu  7  1

I want to order the index by day of week (i.e., Sun, Mon, Tue, Wed, Thu, Fri, Sat). The dataframe with the rearranged/reordered index should look something like this:

我想按星期几(即星期日、星期一、星期二、星期三、星期四、星期五、星期六)对索引进行排序。具有重新排列/重新排序索引的数据框应如下所示:

     A  B
Sun  3  0
Mon  6  7
Tue  2  1
Wed  5  1
Thu  7  1
Fri  4  2

But using df.sort_index() results in an alphabetically-sorted index for df.

但是使用 df.sort_index() 会导致 df 的按字母顺序排序的索引。

How do I explicitly specify the ordering of a dataframe index?

如何明确指定数据帧索引的顺序?

The solution I can think of is to pass the desired index ordering as a list during dataframe creation:

我能想到的解决方案是在数据帧创建期间将所需的索引排序作为列表传递:

df = pd.DataFrame(df, index=['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri'])

What's another way to do this without creating another dataframe?

在不创建另一个数据框的情况下,还有什么方法可以做到这一点?

Thank you.

谢谢你。

采纳答案by Julien Spronck

You can use locand give it a list of indices in the order that you want them:

您可以loc按照您想要的顺序使用并为其提供索引列表:

df = pd.DataFrame({'A': [1, 2, 3, 4, 5, 6, 7],
                   'B': [0, 1, 0, 2, 1, 7, 1]},
                  index=['Sat', 'Tue', 'Sun', 'Fri',
                         'Wed', 'Mon', 'Thu'])
df = df.loc[['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], :]
df
#      A  B
# Sun  3  0
# Mon  6  7
# Tue  2  1
# Wed  5  1
# Thu  7  1
# Fri  4  2
# Sat  1  0

回答by Imaddin Ahmed Mohamed

You only have to add 'week' as register in your dataFrame in the first column.

您只需在第一列的数据框中添加“周”作为注册。

# ascending
df.sort_values('week')
# reverse ascending
df.sort_values('week', ascending=False)

Or maybe this point could be more easy:

或者这点可能更容易:

df.sort_index(inplace=True)
print(df.to_string())