gpt4 book ai didi

python - 计算数据框中的日期从日期时间列到 Python 中的另一列

转载 作者:太空宇宙 更新时间:2023-11-03 15:20:45 25 4
gpt4 key购买 nike

我有一个 dataframe ,其中包含 datetime 列,例如 2014-01-012016-06-05 等。现在我想在 dataframe 中添加一列来计算一年中的某一天(对于给定年份)。

在这个论坛上,我确实找到了一些提示,但我在类型和数据帧方面遇到了困难。所以这工作正常

from datetime import datetime

day_to_calc = today

day_of_year = day_to_calc.timetuple().tm_yday

day_of_year

但我的 day_to_calc 不是今天,而是 df['Date']。但是,如果我尝试这个

df['DOY'] = df['Date'].timetuple().tm_yday

我明白

AttributeError: 'Series' object has no attribute 'timetuple'

好吧,所以我想我可能需要一个 map 功能?所以我正在尝试类似的事情..

df['DOY'] = map (datetime.timetuple().tm_yday,df['Date'])

你们肯定知道这是多么愚蠢;-)(但我仍在学习 Python)

TypeError: descriptor 'timetuple' of 'datetime.datetime' object needs an argument

所以这是有道理的,因为我需要将日期作为参数传递,sooo..尝试

df['DOY'] = datetime.timetuple(df['Date']).tm_yday 

TypeError: descriptor 'timetuple' requires a 'datetime.datetime' object but received a 'Series'

一定有一个简单的方法,但我就是不明白语法:-(

最佳答案

使用dayofyear函数:

import pandas as pd
# first convert date string to datetime with a proper format string
df = pd.DataFrame({'Date':pd.to_datetime(['2014-01-01', '2016-06-05'], format='%Y-%m-%d')})
# calculate day of year
df['DOY'] = df['Date'].dt.dayofyear
print(df)

输出:

        Date  DOY
0 2014-01-01 1
1 2016-06-05 157

关于python - 计算数据框中的日期从日期时间列到 Python 中的另一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43571275/

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