Python 按字母顺序排列数据框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43401903/
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
Python order dataframe alphabetically
提问by Sheron
I would like to reorder dataframe by student name. Does anybody have some suggestions?
我想按学生姓名重新排序数据框。有人有什么建议吗?
df = pd.DataFrame({
'student': [
'monica', 'nathalia', 'anastasia', 'marina', 'ema'
],
'grade' : ['excellent', 'excellent', 'good', 'very good', 'good'
]
})
print (df)
student grade
0 monica excellent
1 nathalia excellent
2 anastasia good
3 marina very good
4 ema good
回答by sgrg
Pre pandas 0.17:
熊猫 0.17 前:
# Sort by ascending student name
df.sort('student')
# reverse ascending
df.sort('student', ascending=False)
Pandas 0.17+ (as mentioned in the other answers):
Pandas 0.17+(如其他答案中所述):
# ascending
df.sort_values('student')
# reverse ascending
df.sort_values('student', ascending=False)
回答by James
You can sort a dataframe using the sort_values
method.
您可以使用该sort_values
方法对数据框进行排序。
df.sort_values('student')
回答by qbzenker
try
尝试
df.sort_values(by='student')
or, if you want Z first:
或者,如果你先想要 Z:
df.sort_values(by='student', ascending=False)
回答by piRSquared
pd.DataFrame.sort_values
is the obvious pandas
choice
pd.DataFrame.sort_values
是显而易见的pandas
选择
However, you can use numpy
and reconstruct. This will give you a modest performance boost.
但是,您可以使用numpy
和重建。这将为您带来适度的性能提升。
a = df.student.values.astype(str).argsort()
pd.DataFrame(df.values[a], df.index[a], df.columns)
grade student
2 good anastasia
4 good ema
3 very good marina
0 excellent monica
1 excellent nathalia
回答by everestial007
pandas 0.19.2
熊猫 0.19.2
df.sort_values(by=['contig', 'pos'], ascending=True)
# where contig and pos are the column names. So, you may change for yours.
Note:Use of inplace
is very essential if you want to update the same dataframe. Most of the people run into confusion about when to use/not-use inplace.
注意:inplace
如果要更新相同的数据框,则使用非常重要。大多数人对何时使用/不使用就地感到困惑。
If you want to make a new-dataframe.
如果你想制作一个新的数据框。
df_sorted = df.sort_values(by=['contig', 'pos'], inplace=False, ascending=True)