[英]Python order dataframe alphabetically
我想按学生姓名重新排序 dataframe。 有人有什么建议吗?
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
大熊猫0.17:
# Sort by ascending student name
df.sort('student')
# reverse ascending
df.sort('student', ascending=False)
熊猫0.17+(如其他答案中所述):
# ascending
df.sort_values('student')
# reverse ascending
df.sort_values('student', ascending=False)
您可以使用sort_values
方法对数据sort_values
进行排序。
df.sort_values('student')
尝试
df.sort_values(by='student')
或者,如果你想要Z先:
df.sort_values(by='student', ascending=False)
大熊猫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.
注意:如果要更新相同的数据帧,则使用inplace
非常重要。 大多数人对何时使用/不使用现场感到困惑。
如果你想创建一个新的数据帧。
df_sorted = df.sort_values(by=['contig', 'pos'], inplace=False, ascending=True)
如果您正在读取 csv 文件,则可以执行类似的操作。
df.sort_values(by=['student'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.