栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

python pandas从日期时间提取年份— df ['year'] = df ['date']。year不起作用

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python pandas从日期时间提取年份— df ['year'] = df ['date']。year不起作用

如果您运行的是熊猫的最新版本,则可以使用datetime属性

dt
访问datetime组件:

In [6]:df['date'] = pd.to_datetime(df['date'])df['year'], df['month'] = df['date'].dt.year, df['date'].dt.monthdfOut[6]:        date  Count  year  month0 2010-06-30    525  2010      61 2010-07-30    136  2010      72 2010-08-31    125  2010      83 2010-09-30     84  2010      94 2010-10-29   4469  2010     10

编辑

看起来您正在运行的是较早版本的熊猫,在这种情况下,以下方法将起作用:

In [18]:df['date'] = pd.to_datetime(df['date'])df['year'], df['month'] = df['date'].apply(lambda x: x.year), df['date'].apply(lambda x: x.month)dfOut[18]:        date  Count  year  month0 2010-06-30    525  2010      61 2010-07-30    136  2010      72 2010-08-31    125  2010      83 2010-09-30     84  2010      94 2010-10-29   4469  2010     10

关于为什么它没有将其解析为日期时间,

read_csv
您需要传递列的顺序位置(
[0]
),因为当
True
它尝试解析列时,
[1,2,3]
请参见文档

In [20]:t="""date   Count6/30/2010   5257/30/2010   1368/31/2010   1259/30/2010   8410/29/2010  4469"""df = pd.read_csv(io.StringIO(t), sep='s+', parse_dates=[0])df.info()<class 'pandas.core.frame.Dataframe'>Int64Index: 5 entries, 0 to 4Data columns (total 2 columns):date     5 non-null datetime64[ns]Count    5 non-null int64dtypes: datetime64[ns](1), int64(1)memory usage: 120.0 bytes

因此,如果您将参数传递

parse_dates=[0]
给,
read_csv
to_datetime
加载后无需再调用“日期”列。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/662052.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号