如何将数据帧中的数字填充为固定长度的零,并获得前两位数字



我是Python的初学者,我一直在尝试提取5位数法国邮政编码的前两个数字,以便创建具有法国部门(这是一个两位数代码)的列。对于那些不知道的人来说,法国的邮政编码总是包含5位数字。此外,法语的前九个部门也有5位数字,但以0开头,例如:城市"戛纳"对应的邮政编码是06150,我想提取的部门是06。

然而,在我的数据集中,这九个前部门的邮政编码只用4位数字书写,所以当我提取前两个数字时,我得到了错误的邮政编码:

回到我的戛纳示例,邮政编码写为6150(而不是06150),如果我提取前两位数字,我将得到61(而不是想要的06)。

所以,我决定使用函数str.zfill(5),但我不明白为什么这不起作用:

df['CODE_POSTAL_PERS']= df['CODE_POSTAL_PERS'].astype(str) #Convert into string
df['CODE_POSTAL_PERS'] = df['CODE_POSTAL_PERS'].str.zfill(5) #Supposed to add 0 on 4 digit postal codes
df['Departement']=df['CODE_POSTAL_PERS'].apply(lambda x: str(x)[0:2]) #Extract the two firt digits on a new column called "Departement".

zfill函数没有检测到4位数的邮政编码,所以它不会用0填充邮政编码。我认为我的问题是我的第一行代码,它在每个邮政编码的末尾添加了一个小数(所以zfill函数永远不会检测到4位数,因为有5个小数)。

原列:

CODE_POSTAL_PERS
0   59170
1   33310
2   40250
3   65000
4   60480
5   42152
6   99000
7   99000
8   21190
9   38000

当a这样做时,它会添加一个小数(我不知道为什么):

df['CODE_POSTAL_PERS'].astype(str)
0         59170.0
1         33310.0
2         40250.0
3         65000.0
4         60480.0
5         42152.0
6         99000.0
7         99000.0
8         21190.0
9         38000.0

如果astype(str)函数没有添加一个小数,我认为它会工作。感谢所有为我解决问题的人!

不确定这种类型对你是否有用。您需要字符串还是整数?我很确定你已经想到了,当你转换一个整数类型的字符串,比如'06150',零将被删除,因为它对整数没有意义,对吧?我认为需要用字符串来表示

这里的另一件事是保持简单。如果要使用字符串,那么可以使用插值方法将变量值与字符串混合,例如:

df = {}
df['CODE_POSTAL_PERS'] = '6150'
# so far so good, now we're going to interpolate the string
# adding a zero at the begining of the string, by using python's f-String:
df['CODE_POSTAL_PERS'] = f"0{df['CODE_POSTAL_PERS']}"
df['Departement'] = df['CODE_POSTAL_PERS'][:2]
print(df['Departement'])
# prints: 06

你可以在这里查看示例:
https://py3.codeskulptor.org/user306_9ZOG8jtzKu_0.py

其他资源:

  • Python f-String(如何插值工作)
    https://realpython.com/python-f-strings/#f-strings-a-new-and-improved-way-to-format-strings-in-python

最新更新