如何将列转换为 pandas 的一个日期时间列? [英] How to convert columns into one datetime column in pandas?
本文介绍了如何将列转换为 pandas 的一个日期时间列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在每一列中都有一个整数。
在数据框中有没有一个Pythonic方法将所有三列转换成datetimes?
From:
MDY苹果橘子
5 6 1990 12 3
5 7 1990 14 4
5 8 1990 15 34
5 9 1990 23 21
into:
Datetimes苹果橘子
1990-6-5 12 3
1990-7-5 14 4
1990-8-5 15 34
1990- 9-5 23 21
解决方案
在0.13(即将到来),这是非常优化和相当快(但仍然相当快0.12);比循环快两个数量级
在[3]中:df
输出[3]:
MDY苹果橘子
0 5 6 1990 12 3
1 5 7 1990 14 4
2 5 8 1990 15 34
3 5 9 1990 23 21
在[4]中:df.dtypes
Out [4]:
M int64
D int64
Y int64
苹果int64
橘子int64
dtype:object
#在0.12中,使用此
在[5]中:pd.to_datetime((df.Y * 10000 + df.M * 100 + df.D))。应用(str),格式='%Y%m%d')
#在0.13以上或这将工作
在[5]:pd.to_datetime(df.Y * 10000 + df.M * 100 + df.D,format ='%Y%m%d')
输出[5]:
0 1990-05-06 00:00:00
1 1990-05-07 00:00:00
2 1990-05-08 00:00:00
3 1990-05-09 00:00:00
dtype:datetime64 [ ns]
I have a dataframe where the first 3 columns are 'MONTH', 'DAY', 'YEAR'
In each column there is an integer. Is there a Pythonic way to convert all three columns into datetimes while there are in the dataframe?
From:
M D Y Apples Oranges
5 6 1990 12 3
5 7 1990 14 4
5 8 1990 15 34
5 9 1990 23 21
into:
Datetimes Apples Oranges
1990-6-5 12 3
1990-7-5 14 4
1990-8-5 15 34
1990-9-5 23 21
解决方案
In 0.13 (coming very soon), this is heavily optimized and quite fast (but still pretty fast in 0.12); both orders of magnitude faster than looping
In [3]: df
Out[3]:
M D Y Apples Oranges
0 5 6 1990 12 3
1 5 7 1990 14 4
2 5 8 1990 15 34
3 5 9 1990 23 21
In [4]: df.dtypes
Out[4]:
M int64
D int64
Y int64
Apples int64
Oranges int64
dtype: object
# in 0.12, use this
In [5]: pd.to_datetime((df.Y*10000+df.M*100+df.D).apply(str),format='%Y%m%d')
# in 0.13 the above or this will work
In [5]: pd.to_datetime(df.Y*10000+df.M*100+df.D,format='%Y%m%d')
Out[5]:
0 1990-05-06 00:00:00
1 1990-05-07 00:00:00
2 1990-05-08 00:00:00
3 1990-05-09 00:00:00
dtype: datetime64[ns]
这篇关于如何将列转换为 pandas 的一个日期时间列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文