Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

python - no of days to previous and next year - 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')

I would like to get the number of days to the previous and next year.

I am able to get the previous and next year using the below code

df1['cur_year'] = pd.DatetimeIndex(df1['dates']).year
df1['prev_year'] = (df1['cur_year'] - 1)
df1['next_year'] = (df1['cur_year'] + 1)

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

I have shown a sample output for 2 subjects below.

enter image description here

updated screenshot

u

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's one way to do it:

dates = df['dates'].astype('datetime64')
df1['prev_yr_days'] = dates.dt.dayofyear
df1['next_yr_days'] = dates.dt.is_leap_year.sub(df1['prev_yr_days']).add(366)

Result:

   person_id variable       dates  prev_yr_day  next_yr_days
0         11   date_1  12/30/1961        364.0           2.0
5         11   date_2  07/23/2017        204.0         162.0
1         21   date_1  05/29/1967        149.0         217.0
6         21   date_2  05/29/2017        149.0         217.0
2         31   date_1  02/03/1957         34.0         332.0
7         31   date_2  02/03/2015         34.0         332.0
3         41   date_1   7/27/1959        208.0         158.0
8         41   date_2         NaN          NaN           NaN
4         51   date_1  01/13/1971         13.0         353.0
9         51   date_2         NaN          NaN           NaN

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...