![](/img/trans.png)
[英]Extract day/year from dataframe string column and sum it [Python]
[英]Calculate day of year in dataframe from a datetime column to another column in Python
我有一個帶有datetime
時間列的dataframe
,例如2014-01-01
、 2016-06-05
等。現在我想在dataframe
添加一個列來計算一年中的第幾天(對於給定的年份)。
在這個論壇上,我確實確實找到了一些提示,但我正在努力解決類型和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:“系列”對象沒有屬性“timetuple”
好的,所以我想我可能需要一個地圖功能? 所以我正在嘗試類似..
df['DOY'] = map (datetime.timetuple().tm_yday,df['Date'])
你們肯定知道那是多么愚蠢;-)(但我仍在學習 Python)
TypeError: 'datetime.datetime' 對象的描述符 'timetuple' 需要參數
所以這是有道理的,因為我需要將日期作為參數傳遞,sooo ..嘗試
df['DOY'] = datetime.timetuple(df['Date']).tm_yday
TypeError: 描述符 'timetuple' 需要一個 'datetime.datetime' 對象但收到了一個 '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
我注意到上面的答案沒有詳細說明,所以我在下面提供了一個更具解釋性的答案。
嘗試以下操作:
import pandas as pd
# Create a pandas datetime range for the year 2022
passed_2022 = pd.date_range('2022-01-01', '2022-12-31')
# Convert the datetime range to a list of strings in the format 'YYYY-MM-DD'
passed_2022_list = [i.strftime('%Y-%m-%d') for i in passed_2022]
# Create a DataFrame
data = pd.DataFrame({'datetime': passed_2022_list})
# Filter the data DataFrame to only include dates in the passed_2022 list
data = data[data['datetime'].isin(passed_2022_list)]
# Count the number of rows in the filtered DataFrame
num_days_passed = len(data)
# Create a new DataFrame with 'datetime' and 'DAYS_OF_YEAR' columns
result = pd.DataFrame({'datetime': passed_2022_list,
'DAYS OF YEAR': range(1, num_days_passed+1)})
# Print the result of the DataFrame
print(result)
輸出:
datetime DAYS OF YEAR
0 2022-01-01 1
1 2022-01-02 2
2 2022-01-03 3
3 2022-01-04 4
4 2022-01-05 5
.. ... ...
360 2022-12-27 361
361 2022-12-28 362
362 2022-12-29 363
363 2022-12-30 364
364 2022-12-31 365
[365 rows x 2 columns]
Process finished with exit code 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.