【问题标题】:Why dtype is different when converting to a category from an object or str?为什么从 object 或 str 转换为类别时 dtype 不同?
【发布时间】:2026-01-29 01:40:01
【问题描述】:

为什么在 pandas 中将列转换为类别时会收到两种不同的行为?

举个例子,假设我用

创建了一个数据框
>>> import pandas as pd
>>> import numpy as np
>>> pd.__version__
u'0.22.0'
>>> np.__version__
'1.14.0'
>>> df = pd.DataFrame(columns=['nombre'], data=[1,2,3,4])

现在我将我的列转换为一个对象:

>>> df['nombre'] = df['nombre'].astype('object')
>>> print(df['nombre'].dtype)
object

dtype 现在是对象。

>>> df['nombre'] = df['nombre'].astype('category')
>>> print(df['nombre'].cat.categories.dtype.name)
int64

转换为类别后,内部dtype为int64。

让我们重新开始一个新的数据框

>>> del df
>>> df = pd.DataFrame(columns=['nombre'], data=[1,2,3,4])

这一次,我们将内部列转换为'str'

>>> df['nombre'] = df['nombre'].astype('str')
>>> print(df['nombre'].dtype)
object

内部表示是一个对象。这是有道理的,因为我们转换为“str”。

>>> df['nombre'] = df['nombre'].astype('category')
>>> print(df['nombre'].cat.categories.dtype.name)
object

转换为类别后,内部dtype现在是object,和我们之前收到的int64不一样?

所以我的问题如下,为什么在从对象 dtype 转换为类别时会收到两种不同的行为?

【问题讨论】:

    标签: python pandas categories


    【解决方案1】:

    .astype(object) 不会将数字转换为字符串。它将数字转换为相应的 Python 对象(在您的示例中,numpy.int64 转换为 Python int)。

    例如,

    df = pd.DataFrame(columns=['nombre'], data=[1,2,3,4])
    
    type(df['nombre'][0])
    Out[64]: numpy.int64
    
    
    df['nombre'] = df['nombre'].astype('object')
    
    type(df['nombre'][0])
    Out[66]: int
    

    但是当您使用astype(str) 时,它会将所有内容都转换为字符串。在这样做的同时,它也将系列转换为对象系列。这是因为这是唯一可以保存字符串的 dtype。

    df['nombre'] = df['nombre'].astype('str')
    
    type(df['nombre'][0])
    Out[69]: str
    

    所以这只是与您的输入数据有关。在你传递整数的第一个中,你得到一个整数数组。在第二个中传递字符串,你会得到一个对象数组。

    此外,术语“内部 dtype”在这里可能不合适。这是包含类别的 Series 的 dtype;不是他们的代码。在这两个示例中,df['nombre'].cat.codes 是内部表示,其 dtype 是 int8

    【讨论】: