我有一个这样的数据帧:
print(df)
0 1 2
0 354.7 April 4.0
1 55.4 August 8.0
2 176.5 December 12.0
3 95.5 February 2.0
4 85.6 January 1.0
5 152 July 7.0
6 238.7 June 6.0
7 104.8 March 3.0
8 283.5 May 5.0
9 278.8 November 11.0
10 249.6 October 10.0
11 212.7 September 9.0
如您所见,月份不是按日历顺序排列的。因此,我创建了第二列来获取每个月对应的月份号(1-12)。在此基础上,如何根据日历月份的顺序对数据帧进行排序?
例子:
假设你有一个值为1和0的列,你想要分离并只使用一个值,那么:
// furniture is one of the columns in the csv file.
allrooms = data.groupby('furniture')['furniture'].agg('count')
allrooms
myrooms1 = pan.DataFrame(allrooms, columns = ['furniture'], index = [1])
myrooms2 = pan.DataFrame(allrooms, columns = ['furniture'], index = [0])
print(myrooms1);print(myrooms2)
作为另一种解决方案:
而不是创建第二列,你可以对你的字符串数据(月份名)进行分类,并像这样排序:
df.rename(columns={1:'month'},inplace=True)
df['month'] = pd.Categorical(df['month'],categories=['December','November','October','September','August','July','June','May','April','March','February','January'],ordered=True)
df = df.sort_values('month',ascending=False)
它将按照您在创建Categorical对象时指定的月份名称为您提供有序数据。