Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/amazon-web-services/12.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_Pandas_Dataframe_Datetime - Fatal编程技术网

Python 如何将数据帧中的列转换为时间序列?

Python 如何将数据帧中的列转换为时间序列?,python,pandas,dataframe,datetime,Python,Pandas,Dataframe,Datetime,因此,我从数据框中选择了3列,以便创建一个时间序列,然后绘制: booking_date = pd.DataFrame({'day': hotel_bookings_cleaned["arrival_date_day_of_month"], 'month': hotel_bookings_cleaned["arrival_date_month"],

因此,我从数据框中选择了3列,以便创建一个时间序列,然后绘制:

booking_date = pd.DataFrame({'day': hotel_bookings_cleaned["arrival_date_day_of_month"],
                             'month': hotel_bookings_cleaned["arrival_date_month"],
                             'year': hotel_bookings_cleaned["arrival_date_year"]})
输出如下所示:

day month   year
0   1   July    2015
1   1   July    2015
2   1   July    2015
3   1   July    2015
4   1   July    2015
我试着用

dates = pd.to_datetime(booking_date)
但是收到了错误信息

ValueError: Unable to parse string "July" at position 0
我假设我需要先将Month列转换为数值,然后才能将其转换为datetime,但我无法使任何解析器工作。

试试这个

dates = pd.to_datetime(booking_date.astype(str).agg('-'.join, axis=1), format='%d-%B-%Y')

Out[13]:
0   2015-07-01
1   2015-07-01
2   2015-07-01
3   2015-07-01
4   2015-07-01
dtype: datetime64[ns]

不确定这是否比上一个答案更有效,但您可以使用字典映射将字符串列转换为整数,以适合pandas希望使用的格式

但我还没能让任何解析器工作。你能分享相关的代码吗?
month_map = {
'January':1,
'February':2,
'March':3,
'April':4,
'May':5,
'June':6,
'July':7,
'August':8,
'September':9,
'October':10,
'November':11,
'December':12
}

dates = pd.DataFrame({
    'day':booking_date.day,
    'month':booking_date.month.apply(lambda x: month_map[x]),
    'year':booking_date.year
})
ts = pd.to_datetime(dates)