如何从日期时间系列中提取月份和年份并将它们存储到两个单独的列中?

How to extract month and year from a datetime series and store them into two separate columns?

我有一个包含 Date 列的数据框,其中包含日期时间对象。我可以从 Date 列中提取月份和年份,并使用下面的代码将它们存储在相应名称的列中。

df["Month"] = df["Date"].dt.month
df["Year"] = df["Date"].dt.year

但是有没有办法只用一行就可以做到这一点?

你可以这样做:

df['Month'], df['Year'] = df["Date"].dt.month, df["Date"].dt.year