代码之家  ›  专栏  ›  技术社区  ›  Todd Shannon

无法更改dtype pandas python[重复]

  •  0
  • Todd Shannon  · 技术社区  · 6 年前

    我正在处理一个数据帧 pandas 我有一个专栏 int64 数据类型。我需要将这个数据类型转换为一个字符串,这样我就可以对字符进行切片,取5个字符列的前3个字符。代码如下:

    trainer_pairs[:, 'zip5'] = trainer_pairs.zip5.astype(dtype='object')
    trainer_pairs.zip5.dtype
    dtype('O')
    

    我已经确认数据类型是 object 但是当我尝试使用 str.slice() 在专栏上,我仍然看到:

    0      NaN
    1      NaN
    2      NaN
    3      NaN
    4      NaN
    5      NaN
    6      NaN
    7      NaN
    

    如何成功更新数据类型以运行此字符串方法?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Wen-Ben    6 年前

    这里你应该用 astype(str)

    trainer_pairs['zip5'] = trainer_pairs.zip5.astype(str)
    

    关于你的错误

    df=pd.DataFrame({'zip':[1,2,3,4,5]})
    df.zip.astype(object)
    Out[4]: 
    0    1
    1    2
    2    3
    3    4
    4    5
    Name: zip, dtype: object
    

    即使转换为对象,它们仍然 int ,使用类型执行切片 int float 将返回值为 NaN . 请检查

    df.zip.astype(object).apply(type)
    Out[5]: 
    0    <class 'int'>
    1    <class 'int'>
    2    <class 'int'>
    3    <class 'int'>
    4    <class 'int'>
    Name: zip, dtype: object
    
    df.zip.astype(str).apply(type)
    Out[6]: 
    0    <class 'str'>
    1    <class 'str'>
    2    <class 'str'>
    3    <class 'str'>
    4    <class 'str'>
    Name: zip, dtype: object