簡體   English   中英

Pandas 1.0 從年份和日期創建月份列

[英]Pandas 1.0 create column of months from year and date

我有一個數據框df ,其值為:

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

我正在嘗試創建一個新的MonthIdx列:

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

但我收到錯誤:

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

以下是所需的輸出:

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

因此,您可以在一系列中填充月份值,然后重新格式化以獲取所有值的日期時間:

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')

這會給你:

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

您可以將日期重新格式化為字符串以完全匹配您的格式:

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

給你:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM