Python的 – 作为string加载到一个数据框的邮政编码?
我使用pandas来加载包含邮政编码的Excel电子表格(例如32771)。 邮政编码在电子表格中以5位数字串存储。 当他们被拉入DataFrame使用命令…
xls = pd.ExcelFile("5-Digit-Zip-Codes.xlsx") dfz = xls.parse('Zip Codes')
他们被转换成数字。 所以'00501'变成了501。
所以我的问题是,我如何:
一个。 加载DataFrame并保存Excel文件中存储的邮政编码的stringtypes?
湾 将DataFrame中的数字转换为五位数的string,例如“501”变成“00501”?
作为一种解决方法,您可以使用Series.str.zfill
将int
s转换为长度为5的填充string:
df['zipcode'] = df['zipcode'].astype(str).str.zfill(5)
演示:
import pandas as pd df = pd.DataFrame({'zipcode':['00501']}) df.to_excel('/tmp/out.xlsx') xl = pd.ExcelFile('/tmp/out.xlsx') df = xl.parse('Sheet1') df['zipcode'] = df['zipcode'].astype(str).str.zfill(5) print(df)
产量
zipcode 0 00501
str(my_zip).zfill(5)
要么
print("{0:>05s}".format(str(my_zip)))
是许多方法中的2个来做到这一点
您可以使用自定义转换器避免pandas的types推理,例如,如果'zipcode'
是带有zipcode的列标题:
dfz = xls.parse('Zip Codes', converters={'zipcode': lambda x:x})
这可能是一个错误,因为该列最初是string编码,在这里成为一个问题