我正在使用pandas中的dataframe,并且有一个具有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如何成功地更新数据类型,以便运行此字符串方法?
发布于 2019-01-02 23:12:16
在这里您应该使用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即使转换为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: objecthttps://stackoverflow.com/questions/54014341
复制相似问题