上一年和下一年的天数- pandas [英] no of days to previous and next year - Pandas
本文介绍了上一年和下一年的天数- pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的数据帧
I have a data frame like as shown below
df1 = pd.DataFrame({'person_id': [11, 21, 31, 41, 51],
'date_1': ['12/30/1961', '05/29/1967', '02/03/1957', '7/27/1959', '01/13/1971'],
'date_2': ['07/23/2017','05/29/2017','02/03/2015',np.nan,np.nan]})
df1 = df1.melt('person_id', value_name='dates')
我想获得到上一年和明年的天数。
我能够获得前一天和明年明年使用以下代码
df1['cur_year'] = pd.DatetimeIndex(df1['dates']).year
df1['prev_year'] = (df1['cur_year'] - 1)
df1['next_year'] = (df1['cur_year'] + 1)
您可以看到 year
的值在不断变化每行,而且我没有固定的基准日期,如何计算与 31/12
前一年, 01/01
次年。
As you can see that the year
values are constantly changing for each row and I don't have a fixed baseline date, how can I calculate the difference in days to dates like 31/12
for the previous year and 01/01
for the next year.
请注意,获取天数时不包括结束日期
Please note that end date is not included while getting the number of days
我已经显示了示例输出以下2个科目。
I have shown a sample output for 2 subjects below.
更新的屏幕截图
推荐答案
据我了解,您可以尝试;
From what i understand, you can try;
df1['dates'] = pd.to_datetime(df1['dates'])
out = df1.assign(prev_yr_days=df1['dates'].dt.dayofyear,
next_yr_days=((df1['dates'] + pd.offsets.YearEnd(0)) - df1['dates']).dt.days.add(1))
person_id variable dates prev_yr_days next_yr_days
0 11 date_1 1961-12-30 364.0 2.0
5 11 date_2 2017-07-23 204.0 162.0
1 21 date_1 1967-05-29 149.0 217.0
6 21 date_2 2017-05-29 149.0 217.0
2 31 date_1 1957-02-03 34.0 332.0
7 31 date_2 2015-02-03 34.0 332.0
3 41 date_1 1959-07-27 208.0 158.0
8 41 date_2 NaT NaN NaN
4 51 date_1 1971-01-13 13.0 353.0
9 51 date_2 NaT NaN NaN
这篇关于上一年和下一年的天数- pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文