Python 从无序日期在熊猫中创建datetime对象

Python 从无序日期在熊猫中创建datetime对象,python,python-3.x,pandas,datetime,Python,Python 3.x,Pandas,Datetime,我有一个熊猫的数据框,看起来像这样 Year Month Month_index Rainfall 1900 Jan 1 4.8 1901 Jan 1 5 . . . 1900 Feb 2 3.2 1901 Feb 2 4.3 . . 要使用datetime索引,我需要将其重新排列为- Year Month Month_index Rainfall 1900 Jan 1

我有一个熊猫的数据框,看起来像这样

Year Month Month_index Rainfall
1900 Jan   1            4.8
1901 Jan   1            5
.
.
.
1900 Feb   2            3.2
1901 Feb   2            4.3
.
.
要使用datetime索引,我需要将其重新排列为-

Year Month Month_index Rainfall
1900 Jan   1            4.8
1900 Feb   2            3.2
.
.
1901 Jan   1            5
1901 Feb   2            4.3
.
.
当然有整整12个月的时间,我只是简单地讲一下。我对python相当陌生,所以我不知道是否有命令可以做到这一点。 提前谢谢你

编辑:以下是我目前使用的代码-

import csv
#import pyexcel-io as pi
import numpy as np
import pandas as pd
import dateutil
#Read data from csv file into dataframe
df =pd.read_csv('/Users/Gingeraffe/Documents/University/3rd_year/Bureau_Research/Notebooks/Data/rainfall_SW_WA.csv')

months = df.columns[1:]
#Melt is putting months down a column and the data down another column. 
Problem is ' jan jan jan... feb feb feb..' etc. instead of 'jan feb mar.. etc'
df = pd.melt(df, id_vars='Year', value_vars=months, var_name='Month')
df.insert(2,'Month_index',0)
M = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'June':6, 'July':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12}
df.Month_index = df.Month.map(M) 

使用您的三列创建一个
datetime
系列,然后我们可以使用这三列进行排序:

s = pd.to_datetime(
        df[['Year', 'Month']].astype(str).sum(1), format='%Y%b'
)
最后,排序:

df.iloc[s.sort_values().index]

将熊猫作为pd导入
d={'Year':[1900190119001901],'Month':['Jan','Jan','Feb','Feb'],'Month_index':[1,1,2,2],'raining':[4.8,5,3.2,4.3]}
df=pd.DataFrame(数据=d)
df=df.sort(['Year','Month_index'])
#dataframe现在应该包含已排序的dataframe

欢迎来到SO。你能更详细地描述一下你的问题吗?例如,通过添加描述问题的代码、命令或屏幕截图。还请查看帮助中心,尤其是和。谢谢,谢谢!我所要添加的就是df=df.iloc[etc]来让它工作。
   Year Month Month_index Rainfall
0  1900   Jan           1      4.8
2  1900   Feb           2      3.2
1  1901   Jan           1      5.0
3  1901   Feb           2      4.3
   import pandas as pd  
   d = {'Year' : [1900,1901,1900,1901], 'Month' : ['Jan','Jan','Feb','Feb'] , 'Month_index' : [1,1,2,2], 'Rainfall' : [4.8,5,3.2,4.3]}  
   df = pd.DataFrame(data=d)  
   df = df.sort(['Year','Month_index'])  
   #dataframe <df> should now contain the sorted dataframe