【发布时间】:2017-01-03 13:40:54
【问题描述】:
我在 Pandas 中读取了一个 SQL 查询,其值以 dtype 'object' 的形式出现,尽管它们是字符串、日期和整数。我能够将日期“对象”转换为 Pandas 日期时间 dtype,但在尝试转换字符串和整数时出现错误。
这是一个例子:
>>> 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
将df['date'] 转换为日期时间有效:
>>> 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]
但在尝试将df['purchase'] 转换为整数时出现错误:
>>> 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'
注意:当我尝试 .astype('float') 时,我遇到了类似的错误
当尝试转换为字符串时,似乎什么也没有发生。
>>> df['id'].apply(str)
1 abc1
2 abc2
3 abc3
4 abc4
Name: id, dtype: object
【问题讨论】:
-
我猜,试试
df['purchase'].astype(str).astype(int) -
没有字符串 dtype。它保持为对象。对于另一个,尝试更通用的
pd.to_numeric(df['purchase']),如果成功,您可以添加.astype(int)。 -
@piRSquared - 是的,这行得通。
-
@ayhan - 我在尝试 pd.to_numeric 时收到此错误 -
TypeError: Invalid object type -
如果列包含 NaN 和整数,则接受的答案将不起作用。为此,如果您有 pandas 1.x,则需要使用
convert_dtypes,或者在旧版本上使用infer_objects。