我正在尝试通过 Pandas 读取 csv 文件。
pd.read_csv('zip_mapping.gz',compression='gzip' ,header=None, sep=',')
但不知何故我在 zip 中读取为 float,比如
0 501.0
1 1220.0
2 1509.0
3 1807.0
4 2047.0
因为我在读取数据之前不知道zip在哪一列,所以我无法在pd.read_csv中设置dtype。
我想将 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'
实际上我想将 float 中的 zip 转换为 str 之类的 501, 1220, 1509, 1807, 2047 然后我可以进一步填充前导零。
有什么建议吗? 谢谢。
请您参考如下方法:
您可以使用Series.astype 方法将float 转换为int 然后再转换为string,这里我使用df 来引用您从csv 中读取的数据框和df.zip 引用 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
