python - 按日期对列进行排序

标签 python pandas dataframe

我正在尝试对“Mon18”表中的“月份”列进行排序,使其从一月到十二月运行及其相应的计数。当我尝试对列进行排序时,它会按最高计数或按字母顺序对“月”列进行排序。请参阅下面的示例:

print (df)
            Months  Count
10      April 2018    684
3      August 2018   1098
1    December 2018   1207
11   February 2018    642
8     January 2018    847
5        July 2018   1040
6        June 2018    986
9       March 2018    809
7         May 2018    854
0    November 2018   1215
2     October 2018   1128
4   September 2018   1062

最佳答案

想法是将列转换为日期时间并使用 Series.argsort对于传递给 DataFrame.iloc 的索引:

df = df.iloc[pd.to_datetime(df['Months'], format='%B %Y').argsort()]
print (df)
            Months  Count
8     January 2018    847
11   February 2018    642
9       March 2018    809
10      April 2018    684
7         May 2018    854
6        June 2018    986
5        July 2018   1040
3      August 2018   1098
4   September 2018   1062
2     October 2018   1128
0    November 2018   1215
1    December 2018   1207

关于python - 按日期对列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58996399/

相关文章:

python - 如何读取多个csv文件并合并它们?

Python Pandas 如何将一个数据帧中的日期与另一个数据帧中的日期进行比较?

python - 在 Pandas 中,如何从单词列表或单词集中选择数据框中的短语?

python - 在python中读取损坏的文件

python - 使用 Pandas 从 Excel 转换为 CSV,我有多个可能的 Excel 工作表名称

python - 使用来自 pandas 中其他两列的匹配项的值创建新列

python - Pandas:如何将 cProfile 输出存储在 Pandas DataFrame 中?

python - 如何选择元组列表中递增的元素?

python - pygame 中的 surface.blit() 函数是什么?它有什么作用?它是如何工作的?

python - 有效获取 np.datetime64 元素列表中不同日期的数量