如何在熊猫中提取年,月,日?

yan*_*hen 0 pandas

我有一个数据框,其中有一个名为'fecha_dato'的列.它存储日期,如'2016-05-28'.我想从fecha_dato中提取2016,05和28作为int作为名为年,月和日的新列.我使用迭代器方式,但它太慢了.有没有有效的方法来做到这一点?

jez*_*ael 11

你需要dt.year,dt.month并且dt.day:

df['year'] = df.fecha_dato.dt.year
df['month'] = df.fecha_dato.dt.month
df['day'] = df.fecha_dato.dt.day
Run Code Online (Sandbox Code Playgroud)

样品:

df = pd.DataFrame({'fecha_dato':['2016-05-28','2016-06-28','2016-07-28']})

#if dtype is not datetime, cast it
df.fecha_dato = pd.to_datetime(df.fecha_dato)

df['year'] = df.fecha_dato.dt.year
df['month'] = df.fecha_dato.dt.month
df['day'] = df.fecha_dato.dt.day
print (df)
  fecha_dato  year  month  day
0 2016-05-28  2016      5   28
1 2016-06-28  2016      6   28
2 2016-07-28  2016      7   28
Run Code Online (Sandbox Code Playgroud)