我正在尝试对“ 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
答案 0 :(得分:1)
想法将列转换为日期时间,并将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