如何提取 pandas 年,月和日? [英] How to extract the year, month and day in Pandas?

查看:69
本文介绍了如何提取 pandas 年,月和日?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,其中有一个名为"fecha_dato"的列.它将日期存储为"2016-05-28".我想将2016、05和28从fecha_dato中提取为int,作为新的列,分别命名为year,month和day.我使用迭代器方式,但速度太慢. 有什么有效的方法可以做到这一点吗?

I have a dataframe which has a column named 'fecha_dato'. It stores the date like '2016-05-28'. I want to extract the 2016, 05 and 28 as int from fecha_dato as new columns named year, month and day. I use the iterator way but it is too slow. Is there any efficient way to do this ?

推荐答案

您需要 dt.month

You need dt.year, dt.month and dt.day:

df['year'] = df.fecha_dato.dt.year
df['month'] = df.fecha_dato.dt.month
df['day'] = df.fecha_dato.dt.day

示例:

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

这篇关于如何提取 pandas 年,月和日?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆