我正在尝试添加datetime.datetime和datetime.time来获取一列。我正在尝试结合:
import datetime as dt
dt.datetime.combine(myDF['Date'].astype(dt.date), myDF['Time'].astype(dt.time))
但我明白了:
TypeError: combine() argument 1 must be datetime.date, not Series
我正在尝试这个:
myDF['Date'] + myDF['Time']
但我得到
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.time'
有人知道,我怎么能把我的两个colums组合起来?
Date Time
0 2011-08-08 00:00:00 08:10:00
1 2011-08-08 00:00:00 08:10:00
2 2011-08-08 00:00:00 08:10:00
3 2011-08-08 00:00:00 11:20:00
4 2011-08-08 00:00:00 12:25:00
5 2011-08-08 00:00:00 14:20:00
答案 0 :(得分:1)
您正在尝试合并整列,但datetime.combine()
不知道如何应用于单独的列。
def combine_cols(row):
return dt.datetime.combine(
row['Date'].date(), row['Time'])
myDF.apply(combine_cols, axis=1)
axis=1
告诉apply()
将每一行传递给callable。
演示:
>>> import pandas as pd
>>> import datetime as dt
>>> myDF = pd.DataFrame({
... 'Date': pd.Series([dt.datetime(2011, 8, 8)] * 6),
... 'Time': pd.Series([dt.time(8, 10), dt.time(8, 10), dt.time(8, 10), dt.time(11, 20), dt.time(12, 25), dt.time(14, 20)])
... })
>>> myDF
Date Time
0 2011-08-08 08:10:00
1 2011-08-08 08:10:00
2 2011-08-08 08:10:00
3 2011-08-08 11:20:00
4 2011-08-08 12:25:00
5 2011-08-08 14:20:00
>>> def combine_cols(row):
... return dt.datetime.combine(
... row['Date'].date(), row['Time'])
...
>>> myDF.apply(combine_cols, axis=1)
0 2011-08-08 08:10:00
1 2011-08-08 08:10:00
2 2011-08-08 08:10:00
3 2011-08-08 11:20:00
4 2011-08-08 12:25:00
5 2011-08-08 14:20:00
dtype: datetime64[ns]