[英]Python order dataframe alphabetically
I would like to reorder dataframe by student name.我想按学生姓名重新排序 dataframe。 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
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): 熊猫0.17+(如其他答案中所述):
# ascending
df.sort_values('student')
# reverse ascending
df.sort_values('student', ascending=False)
您可以使用sort_values
方法对数据sort_values
进行排序。
df.sort_values('student')
try 尝试
df.sort_values(by='student')
or, if you want Z first: 或者,如果你想要Z先:
df.sort_values(by='student', ascending=False)
pd.DataFrame.sort_values
is the obvious pandas
choice pd.DataFrame.sort_values
是明显的pandas
选择
However, you can use numpy
and reconstruct. 但是,您可以使用numpy
和reconstruct。 This will give you a modest performance boost. 这将为您带来适度的性能提升。
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
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. 注意:如果要更新相同的数据帧,则使用inplace
非常重要。 Most of the people run into confusion about when to use/not-use inplace. 大多数人对何时使用/不使用现场感到困惑。
If you want to make a new-dataframe. 如果你想创建一个新的数据帧。
df_sorted = df.sort_values(by=['contig', 'pos'], inplace=False, ascending=True)
You can do something similar if you're reading from a csv file.如果您正在读取 csv 文件,则可以执行类似的操作。
df.sort_values(by=['student'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.