英文:
pandas split year from a year-date-time column
问题
你可以尝试以下代码来将日期时间列拆分为只包含年份的新列:
df['year'] = df['date_time'].str.split('-').str[0]
这将创建一个名为'year'的新列,其中包含每个日期时间值中的年份部分。
英文:
I have a dataframe 'df' with one column called 'date_time' that has values in this format "2018-01-01T00:00:00-05:00".
I want to split it so I have just the year "2018" in a new column.
I tried
df['year'] = df["date_time"].str.split("-", n=1, expand = False)
I get a new column called 'year' with a list [2018, 01-01T00:00:00-05:00]
But I want to split it so I have just the year 2018 in the new column.
答案1
得分: 0
I understand. Here is the translated code:
df['year'] = pd.to_datetime(df['date_time'], errors="coerce").dt.year
英文:
IIUC use:
df['year'] = pd.to_datetime(df['date_time'], error="coerce").dt.year
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论