问题描述
我有一个带有日期列的数据框.持续时间为365天,从2017年11月11日开始,至2018年11月11日结束.
I have a dataframe with a date column. The duration is 365 days starting from 02/11/2017 and ending at 01/11/2018.
Date
02/11/2017
03/11/2017
05/11/2017
.
.
01/11/2018
我要添加一个名为Day_Of_Year的相邻列,如下所示:
I want to add an adjacent column called Day_Of_Year as follows:
Date Day_Of_Year
02/11/2017 1
03/11/2017 2
05/11/2017 4
.
.
01/11/2018 365
如果这是一个非常基本的问题,我深表歉意,但不幸的是,我无法从这个问题入手.
I apologize if it's a very basic question, but unfortunately I haven't been able to start with this.
我可以使用datetime(),但无论年份如何,都将返回值,例如1月1日为1,2月2日为2等.因此,这对我不起作用.
I could use datetime(), but that would return values such as 1 for 1st january, 2 for 2nd january and so on.. irrespective of the year. So, that wouldn't work for me.
推荐答案
首先转换列 to_datetime
,然后减去 datetime
,转换为 days
并添加 1
:
First convert column to_datetime
and then subtract datetime
, convert to days
and add 1
:
df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y')
df['Day_Of_Year'] = df['Date'].sub(pd.Timestamp('2017-11-02')).dt.days + 1
print (df)
Date Day_Of_Year
0 02/11/2017 1
1 03/11/2017 2
2 05/11/2017 4
3 01/11/2018 365
或通过列的第一个值减去
Or subtract by first value of column:
df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y')
df['Day_Of_Year'] = df['Date'].sub(df['Date'].iat[0]).dt.days + 1
print (df)
Date Day_Of_Year
0 2017-11-02 1
1 2017-11-03 2
2 2017-11-05 4
3 2018-11-01 365
这篇关于从特定日期开始的年中的天值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!