我有一个Pandas DataFrame,其中有3列,如下所示:
df:
day min_from value
2012-10-12 0 0.34
2012-10-12 30 0.36
2012-10-12 60 0.56
df.dtypes
min_from int64
day datetime64[ns]
value float64
我正在尝试创建以下内容
date value
2012-10-12 00:00:00 0.34
2012-10-12 00:30:00 0.36
2012-10-12 00:60:00 0.56
我尝试过:
def create_dt(row):
return str(df['day'])+ ' '+ str(timedelta(minutes=df['min_from']))
df['date_time'] = df.apply(create_dt, axis=1)
但是在应用create_dt时出现以下错误:
TypeError: ('unsupported type for timedelta minutes component: Series', 'occurred at index 0')
答案 0 :(得分:2)
如果您的day
列采用日期时间格式,则可以像这样添加Timedelta
,避免调用apply
(这可能很慢):
# In case day is not datetime yet:
df['date'] = pd.to_datetime(df['day']) + pd.to_timedelta(df['min_from'],unit='m')
# Otherwise
df['date'] = df['day'] + pd.to_timedelta(df['min_from'],unit='m')
>>> df
day min_from value date
0 2012-10-12 0 0.34 2012-10-12 00:00:00
1 2012-10-12 30 0.36 2012-10-12 00:30:00
2 2012-10-12 60 0.56 2012-10-12 01:00:00
答案 1 :(得分:1)
from datetime import timedelta
df['date'] = df.apply(lambda row: row.day + timedelta(minute=row.min_from), axis=1)
将在几分钟内在您的date
中创建一个DataFrame
列