如何按索引对Pandas DataFrame排序? [英] How to sort a Pandas DataFrame by index?

查看:1237
本文介绍了如何按索引对Pandas DataFrame排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当存在如下所示的DataFrame时:

When there is an DataFrame like the following:

import pandas as pd
df = pd.DataFrame([1, 1, 1, 1, 1], index=[100, 29, 234, 1, 150], columns=['A'])

如何完整地按索引和列值的每种组合按索引对该数据框进行排序?

How can I sort this dataframe by index with each combination of index and column value intact?

推荐答案

数据框具有sort_index方法,该方法默认情况下返回副本.通过inplace=True进行操作.

Dataframes have a sort_index method which returns a copy by default. Pass inplace=True to operate in place.

import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())

给我:

     A
1    4
29   2
100  1
150  5
234  3

这篇关于如何按索引对Pandas DataFrame排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆