2017-03-08 138 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

相關問題