我有一个来自数据库的数据框,如下所示: FltDate和ESTAD2都是datetime64 [ns]
>>> print df[['Airport', 'FltDate', 'Carrier', 'ESTAD2']]
Airport FltDate Carrier ESTAD2
0 EDI 2017-06-18 BACJ 1899-12-30 05:35:00
1 EDI 2017-06-18 BA 1899-12-30 06:40:00
2 EDI 2017-06-18 BACJ 1899-12-30 07:00:00
3 EDI 2017-06-18 BA 1899-12-30 07:05:00
4 EDI 2017-06-18 BA 1899-12-30 09:00:00
5 EDI 2017-06-18 I2 1899-12-30 11:05:00
6 EDI 2017-06-18 BA 1899-12-30 11:25:00
7 EDI 2017-06-18 BA 1899-12-30 13:45:00
>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 214 entries, 0 to 213
Data columns (total 12 columns):
Airport 214 non-null object
FltDate 214 non-null datetime64[ns]
<snip>
ESTAD2 214 non-null datetime64[ns]
<snip>
dtypes: datetime64[ns](4), object(8)
memory usage: 20.1+ KB
如何从ESTt2获取日期部分来自FltDate 和时间部分。
对于第0行
,结果应该是这样的2017-06-18 05:35:00 (that is 18Jun2017 of FltDate + 05:35 of ESTAD2)
我可以用上面的结果替换ESTAD2 ..或者创建一个新的列作为FltDateTime。
尝试了各种各样的方法并且失败了...如下所示......添加不成功。
>>> df.FltDate.dt.date
0 2017-06-18
1 2017-06-18
2 2017-06-18
>>> df.ESTAD2.dt.time
0 05:35:00
1 06:40:00
2 07:00:00
答案 0 :(得分:2)
您可以strftime
使用to_datetime
:
df['date'] = pd.to_datetime(df.FltDate.dt.strftime('%Y-%m-%d ') +
df.ESTAD2.dt.strftime('%H:%M:%S'))
print (df)
Airport FltDate Carrier ESTAD2 date
0 EDI 2017-06-18 BACJ 1899-12-30 05:35:00 2017-06-18 05:35:00
1 EDI 2017-06-18 BA 1899-12-30 06:40:00 2017-06-18 06:40:00
2 EDI 2017-06-18 BACJ 1899-12-30 07:00:00 2017-06-18 07:00:00
3 EDI 2017-06-18 BA 1899-12-30 07:05:00 2017-06-18 07:05:00
4 EDI 2017-06-18 BA 1899-12-30 09:00:00 2017-06-18 09:00:00
5 EDI 2017-06-18 I2 1899-12-30 11:05:00 2017-06-18 11:05:00
6 EDI 2017-06-18 BA 1899-12-30 11:25:00 2017-06-18 11:25:00
7 EDI 2017-06-18 BA 1899-12-30 13:45:00 2017-06-18 13:45:00
替代解决方案:
df['date'] = pd.to_datetime(df.FltDate.dt.strftime('%Y-%m-%d ') +
df.ESTAD2.astype(str).str.split().str[1])
print (df)
Airport FltDate Carrier ESTAD2 date
0 EDI 2017-06-18 BACJ 1899-12-30 05:35:00 2017-06-18 05:35:00
1 EDI 2017-06-18 BA 1899-12-30 06:40:00 2017-06-18 06:40:00
2 EDI 2017-06-18 BACJ 1899-12-30 07:00:00 2017-06-18 07:00:00
3 EDI 2017-06-18 BA 1899-12-30 07:05:00 2017-06-18 07:05:00
4 EDI 2017-06-18 BA 1899-12-30 09:00:00 2017-06-18 09:00:00
5 EDI 2017-06-18 I2 1899-12-30 11:05:00 2017-06-18 11:05:00
6 EDI 2017-06-18 BA 1899-12-30 11:25:00 2017-06-18 11:25:00
7 EDI 2017-06-18 BA 1899-12-30 13:45:00 2017-06-18 13:45:00