gpt4 book ai didi

python - Pandas 从日期和整数创建日期时间列

转载 作者:行者123 更新时间:2023-11-30 22:05:37 24 4
gpt4 key购买 nike

我有一个包含 3 列的 Pandas DataFrame,如下所示:

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')

最佳答案

如果您的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

关于python - Pandas 从日期和整数创建日期时间列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52958741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com