简体   繁体   中英

Pandas 1.0 create column of months from year and date

I have a dataframe df with values as:

df.iloc[1:4, 7:9]
    Year  Month
38  2020      4
65  2021      4
92  2022      4

I am trying to create a new MonthIdx column as:

df['MonthIdx'] = pd.to_timedelta(df['Year'], unit='Y') + pd.to_timedelta(df['Month'], unit='M') + pd.to_timedelta(1, unit='D')

But I get the error:

ValueError: Units 'M' and 'Y' are no longer supported, as they do not represent unambiguous timedelta values durations.

Following is the desired output:

df['MonthIdx']
    MonthIdx
38  2020/04/01
65  2021/04/01
92  2022/04/01

So you can pad the month value in a series, and then reformat to get a datetime for all of the values:

month = df.Month.astype(str).str.pad(width=2, side='left', fillchar='0')
df['MonthIdx'] = pd.to_datetime(pd.Series([int('%d%s' % (x,y)) for x,y in zip(df['Year'],month)]),format='%Y%m')

This will give you:

   Year  Month   MonthIdx
0  2020      4 2020-04-01
1  2021      4 2021-04-01
2  2022      4 2022-04-01

You can reformat the date to be a string to match exactly your format:

df['MonthIdx'] = df['MonthIdx'].apply(lambda x: x.strftime('%Y/%m/%d'))

Giving you:

   Year  Month    MonthIdx
0  2020      4  2020/04/01
1  2021      4  2021/04/01
2  2022      4  2022/04/01

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM