pandas从年-日期-时间列中分离年份

huangapple go评论49阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年4月17日 14:01:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76032085.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定