Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 根据月份(非字母表)重新订购数据帧_Python - Fatal编程技术网

Python 根据月份(非字母表)重新订购数据帧

Python 根据月份(非字母表)重新订购数据帧,python,Python,对于数据帧,我们将其称为weather1: Temp Month Apr 61 Jan 32 Jul 69 Oct 43 我想根据实际的日历月顺序对月份进行排序,而不是按字母顺序 我可以做到以下几点: ordered= ['Jan','Apr','Jul','Oct'] df.reindex(ordered) 然而,我正在寻找一种更动态的方法来实现这一点,也许可以使用“日期部分”函数 提前感谢您。已格式化您的数据以制作MCVE: impo

对于数据帧,我们将其称为weather1:

        Temp
Month   
Apr     61
Jan     32
Jul     69
Oct     43
我想根据实际的日历月顺序对月份进行排序,而不是按字母顺序

我可以做到以下几点:

ordered= ['Jan','Apr','Jul','Oct']
df.reindex(ordered)
然而,我正在寻找一种更动态的方法来实现这一点,也许可以使用“日期部分”函数


提前感谢您。

已格式化您的数据以制作MCVE:

import pandas as pd
data = {
    'smonth': ['Apr', 'Jan', 'Jul', 'Oct']
   ,'temp': [61, 32, 69, 43]
}
df = pd.DataFrame(data)
我们有以下数据帧:

  smonth  temp
0    Apr    61
1    Jan    32
2    Jul    69
3    Oct    43
现在,我们将字符串Month(使用
%b
格式设置程序,请参阅)列转换为日期,然后转换为索引,最后提取Month字段:

df['month'] = pd.DatetimeIndex(pd.to_datetime(df['smonth'], format='%b')).month
然后重新编制索引并排序:

df = df.set_index('month').sort_index()
它是这样做的:

      smonth  temp
month             
1        Jan    32
4        Apr    61
7        Jul    69
10       Oct    43
更新

如果我明确再现您的输入,请使用:

df2 = pd.DataFrame(
    data['temp']
   ,index=pd.Index(data['smonth'], name='Month')
   ,columns=['Temp']
)
然后减少到:

df2.index = pd.to_datetime(df2.index, format='%b').month
df2.sort_index(inplace=True)
并返回:

       Temp
Month      
1        32
4        61
7        69
10       43

你可以参考这个答案@Sheshnath我似乎不知道如何使用这个例子来应用于我的,因为索引中只有%b from date。我还得到一个错误“Index”对象没有属性“strftime”