2017-03-08 69 views
2

我试图通过Pandas读取一个csv文件。python将浮点数转换为字符串

pd.read_csv('zip_mapping.gz',compression='gzip' ,header=None, sep=',') 

但不知何故,我在拉链浮法读,像

0  501.0 
1 1220.0 
2 1509.0 
3 1807.0 
4 2047.0 

,因为我不知道zip文件中,列前我在数据读取方面,所以我不能设置PD D型.read_csv。

我想将zip更改为int,但由于缺少值,我得到“无法将NA转换为int”错误。

试图

str(zip).rstrip('0').rstrip('.') 

但得到这个

'0  501.0\n1 1220.0\n2 1509.0\n3 1807.0\n4 2047.0\nName: zip, dtype: float64' 

其实我想转换压缩在浮动到STR像 501,1220,1509,1807,2047 话,我可能会进一步填充前导零。

有什么建议吗? 谢谢。

回答

2

您可以使用Series.astype方法来转换浮动为int然后串,这里我使用df指你从CSV中读取和df.zip来指代拉链列中的数据帧(相应调整):

df.zip.astype(int).astype(str).str.zfill(5) 

#0 00501 
#1 01220 
#2 01509 
#3 01807 
#4 02047 
#Name: zip, dtype: object 

如果NA列,你想保持他们的是:

df['zip'] = df.zip.dropna().astype(int).astype(str).str.zfill(5) 
df 

#  zip 
#0 NaN 
#1 01220 
#2 01509 
#3 01807 
#4 02047 

另一种选择使用字符串格式器:

df.zip.apply(lambda x: x if pd.isnull(x) else "{:05.0f}".format(x)) 

#0  NaN 
#1 01220 
#2 01509 
#3 01807 
#4 02047 
#Name: zip, dtype: object 
+0

这工作正常。谢谢。 – newleaf

+0

只是想知道为什么我使用str(zip),仍然得到dtype为'float64' – newleaf

+0

仍然得到ValueError:无法将NA转换为整数 – newleaf

相关问题