String 无法更改python中的数据类型

String 无法更改python中的数据类型,string,pandas,slice,String,Pandas,Slice,我正在使用pandas中的一个数据帧,我有一个数据类型为int64的列。我需要将此数据类型转换为字符串,以便可以对字符进行切片,取5个字符列的前3个字符。代码如下: trainer_pairs[:, 'zip5'] = trainer_pairs.zip5.astype(dtype='object') trainer_pairs.zip5.dtype dtype('O') 我已经确认数据类型是一个对象,但是当我尝试在列上使用str.slice()时,我仍然得到以下结果: 0 NaN

我正在使用
pandas
中的一个数据帧,我有一个数据类型为
int64
的列。我需要将此数据类型转换为字符串,以便可以对字符进行切片,取5个字符列的前3个字符。代码如下:

trainer_pairs[:, 'zip5'] = trainer_pairs.zip5.astype(dtype='object')
trainer_pairs.zip5.dtype
dtype('O')
我已经确认数据类型是一个
对象
,但是当我尝试在列上使用
str.slice()
时,我仍然得到以下结果:

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

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

这里您应该使用
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
df.zip.astype(对象).apply(类型)
出[5]:
0
1.
2.
3.
4.
名称:zip,数据类型:object
astype(str).apply(type)
出[6]:
0
1.
2.
3.
4.
名称:zip,数据类型:object

trainer\u pairs['zip5']怎么样。astype(str)
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