我正在使用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
如何成功更新数据类型,以便可以运行此字符串方法?
答案 0 :(得分: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
的对象,对类型为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