pandas :将 dtype 'object' 转换为 int [英] Pandas: convert dtype 'object' to int

查看:98
本文介绍了 pandas :将 dtype 'object' 转换为 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将 SQL 查询读入 Pandas,并且这些值以 dtype 'object' 的形式传入,尽管它们是字符串、日期和整数.我能够将日期对象"转换为 Pandas 日期时间数据类型,但在尝试转换字符串和整数时出现错误.

这是一个例子:

<预><代码>>>>将熊猫导入为 pd>>>df = pd.read_sql_query('select * from my_table', conn)>>>df身份证日期购买1 abc1 2016-05-22 12 abc2 2016-05-29 03 abc3 2016-05-22 24 abc4 2016-05-22 0>>>df.dtypes标识对象日期对象购买对象数据类型:对象

df['date'] 转换为日期时间有效:

<预><代码>>>>pd.to_datetime(df['date'])1 2016-05-222 2016-05-293 2016-05-224 2016-05-22名称:日期,数据类型:datetime64[ns]

但是在尝试将 df['purchase'] 转换为整数时出现错误:

<预><代码>>>>df['购买'].astype(int)....pandas.lib.astype_intsafe 中的 pandas/lib.pyx (pandas/lib.c:16667)()pandas/src/util.pxd 在 util.set_value_at (pandas/lib.c:67540)()类型错误:long() 参数必须是字符串或数字,而不是java.lang.Long"

注意:当我尝试 .astype('float')

时,我遇到了类似的错误

当尝试转换为字符串时,似乎什么也没有发生.

<预><代码>>>>df['id'].apply(str)1 abc12 abc23 abc34 abc4名称:id,数据类型:对象

解决方案

根据 @piRSquared 的评论记录对我有用的答案.

我需要先转换为字符串,然后是整数.

<预><代码>>>>df['购买'].astype(str).astype(int)

I've read an SQL query into Pandas and the values are coming in as dtype 'object', although they are strings, dates and integers. I am able to convert the date 'object' to a Pandas datetime dtype, but I'm getting an error when trying to convert the string and integers.

Here is an example:

>>> import pandas as pd
>>> df = pd.read_sql_query('select * from my_table', conn)
>>> df
    id    date          purchase
 1  abc1  2016-05-22    1
 2  abc2  2016-05-29    0
 3  abc3  2016-05-22    2
 4  abc4  2016-05-22    0

>>> df.dtypes
 id          object
 date        object
 purchase    object
 dtype: object

Converting the df['date'] to a datetime works:

>>> pd.to_datetime(df['date'])
 1  2016-05-22
 2  2016-05-29
 3  2016-05-22
 4  2016-05-22
 Name: date, dtype: datetime64[ns] 

But I get an error when trying to convert the df['purchase'] to an integer:

>>> df['purchase'].astype(int)
 ....
 pandas/lib.pyx in pandas.lib.astype_intsafe (pandas/lib.c:16667)()
 pandas/src/util.pxd in util.set_value_at (pandas/lib.c:67540)()

 TypeError: long() argument must be a string or a number, not 'java.lang.Long'

NOTE: I get a similar error when I tried .astype('float')

And when trying to convert to a string, nothing seems to happen.

>>> df['id'].apply(str)
 1 abc1
 2 abc2
 3 abc3
 4 abc4
 Name: id, dtype: object

解决方案

Documenting the answer that worked for me based on the comment by @piRSquared.

I needed to convert to a string first, then an integer.

>>> df['purchase'].astype(str).astype(int)

这篇关于 pandas :将 dtype 'object' 转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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