如何按工作日名称对DataFrame进行排序?我不能使用pd.to_datetime()方法,因为我的日期不是数字。

    Date    Transactions
0   Friday  140.652174
1   Monday  114.000000
2   Saturday    208.826087
3   Sunday  140.565217
4   Thursday    118.217391
5   Tuesday     107.826087
6   Wednesday   105.608696

最佳答案

您可以将column的值转换为ordered categoricals,因此可以使用 sort_values :

cats = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
df['Date'] = pd.Categorical(df['Date'], categories=cats, ordered=True)
df = df.sort_values('Date')
print (df)
        Date  Transactions
1     Monday    114.000000
5    Tuesday    107.826087
6  Wednesday    105.608696
4   Thursday    118.217391
0     Friday    140.652174
2   Saturday    208.826087
3     Sunday    140.565217

或按 Date set_index列创建索引,然后按 reindex 和最后 reset_index 创建索引:

注意:
解决方案仅在列的唯一值有效
df = df.set_index('Date').reindex(cats).reset_index()
print (df)

        Date  Transactions
0     Monday    114.000000
1    Tuesday    107.826087
2  Wednesday    105.608696
3   Thursday    118.217391
4     Friday    140.652174
5   Saturday    208.826087
6     Sunday    140.565217

关于python - 按工作日排序 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53189216/

10-11 02:09