数据帧搜索和修改邮政编码的前导零

2024-06-13 18:45:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据框数据库的位置和邮政编码地址。但邮政编码是通过Excel阅读来解释的。例如,在法国,邮政地址是一个部门代码,后跟城市代码,例如75600(75=巴黎地区,600=内城)

但在一些最初的邮政编码中,例如01200,其解释为1200。如何搜索10000以下的整数值并修改它们?或者如何保持第一个零。如何在数据框中搜索和替换并使用内容(修改内容)


Tags: 数据代码数据库内容地址整数excel地区
3条回答

因此,据我所知,一个可能的解决方案是在邮政编码为<;10000是这样吗?一种方法是将所有条目转换为字符串

import pandas as pd
# example with only two locations in column 0 of a DataFrame 
df = pd.DataFrame([75600, 1200])
# convert all entries in column 0 to string, adding '0' to the beginning when postal code < 10000
df = df[0].apply(lambda x: '0' + str(x) if x < 10000 else str(x))

如果这不是你想要的解决方案,请让我知道

我建议创建一个新的专栏,而不是尝试动态替换

像这样的

例如:

In [42]: df=pd.DataFrame([{"Location": "some_loc", "Code": "75600"}, {"Location": "some_other_loc", "Code": "01200"}, {"Location": "another_loc", "Code": "08100"}])

In [43]: df
Out[43]:
         Location   Code
0        some_loc  75600
1  some_other_loc  01200
2     another_loc  08100

In [46]: df["NewCode"] = [str(int(x)) if int(x) < 10000 else None for x in df["Code"]]

In [47]: df
Out[47]:
         Location   Code NewCode
0        some_loc  75600    None
1  some_other_loc  01200    1200
2     another_loc  08100    8100

df的解=df[0]。应用(lambda x:'0'+str(x),如果x<;10000 else str(x))是完美的。它将代码转换成完整的字符串,然后我可以找到与国家邮政信息相对应的GPS坐标。 非常感谢

相关问题 更多 >