熊猫:将 dtype 'object' 转换为 int

新手上路,请多包涵

我已经将一个 SQL 查询读入 Pandas 并且值以 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

原文由 cyril 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

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

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

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

原文由 cyril 发布,翻译遵循 CC BY-SA 3.0 许可协议

熊猫 >= 1.0

convert_dtypes

(自我)接受的答案没有考虑到对象列中出现 NaN 的可能性。

 df = pd.DataFrame({
     'a': [1, 2, np.nan],
     'b': [True, False, np.nan]}, dtype=object)
df

     a      b
0    1   True
1    2  False
2  NaN    NaN

df['a'].astype(str).astype(int) # raises ValueError

这是因为 NaN 被转换为字符串“nan”,并且进一步尝试强制转换为整数将失败。为避免此问题,我们可以使用 convert_dtypes 将列软转换为其相应的 可空类型

 df.convert_dtypes()

      a      b
0     1   True
1     2  False
2  <NA>   <NA>

df.convert_dtypes().dtypes

a      Int64
b    boolean
dtype: object

如果您的数据中有垃圾文本与您的整数混合,您可以使用 pd.to_numeric 作为初始步骤:

 s = pd.Series(['1', '2', '...'])
s.convert_dtypes()  # converts to string, which is not what we want

0      1
1      2
2    ...
dtype: string

# coerces non-numeric junk to NaNs
pd.to_numeric(s, errors='coerce')

0    1.0
1    2.0
2    NaN
dtype: float64

# one final `convert_dtypes` call to convert to nullable int
pd.to_numeric(s, errors='coerce').convert_dtypes()

0       1
1       2
2    <NA>
dtype: Int64

原文由 cs95 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题