【问题标题】:unable to change dtype pandas python [duplicate]无法更改dtype pandas python [重复]
【发布时间】:2019-05-29 13:45:47
【问题描述】:

我正在使用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

我怎样才能成功地更新数据类型以便我可以运行这个字符串方法?

【问题讨论】:

  • 怎么样:trainer_pairs['zip5'].astype(str)

标签: string pandas slice


【解决方案1】:

这里你应该使用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 ,使用类型为 intfloat 的切片将返回值为 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 2019-06-28
    相关资源
    最近更新 更多