我需要将邮政编码(仅邮政编码)提取到一个新列中进行进一步分析.我在数据清理阶段主要使用pandas.我try 使用此代码之前:

import pandas as pd
df_participant = pd.read_csv('https://storage.googleapis.com/dqlab-dataset/dqthon-participants.csv')

df_participant['postal_code'] = df_participant['address'].str.extract(r'([0-9]\d+)')

print (df_participant[['address','postal_code']].head())

但它不起作用

this is the output: enter image description here

任何帮助都将不胜感激!非常感谢.

推荐答案

str.extract

df_participant['postal_code'] = df_participant['address'].str.extract(r'(\d{5})')

#OR if the length of the postal code changes, just make it \d+ combined with "$"

df_participant['postal_code'] = df_participant['address'].str.extract(r'(\d+)$')

但你在这里不需要它.只需取字符串的最后5位数字,因为邮政编码总是在末尾.

df_participant['postal_code'] = df_participant['address'].str[-5:]

Python相关问答推荐

如何将我的位置与光强度数据匹配到折射图案曲线中?

Python中MongoDB的BSON时间戳

如何在Deliveryter笔记本中从同步上下文正确地安排和等待Delivercio代码中的结果?

如何使用scipy从频谱图中回归多个高斯峰?

韦尔福德方差与Numpy方差不同

如何在Python中将returns.context. DeliverresContext与Deliverc函数一起使用?

使可滚动框架在tkinter环境中看起来自然

为什么sys.exit()不能与subproccess.run()或subprocess.call()一起使用

log 1 p numpy的意外行为

计算组中唯一值的数量

Julia CSV for Python中的等效性Pandas index_col参数

如何在python polars中停止otherate(),当使用when()表达式时?

无法使用DBFS File API路径附加到CSV In Datricks(OSError Errno 95操作不支持)

如果条件不满足,我如何获得掩码的第一个索引并获得None?

创建可序列化数据模型的最佳方法

多处理队列在与Forking http.server一起使用时随机跳过项目

字符串合并语法在哪里记录

从嵌套的yaml创建一个嵌套字符串,后面跟着点

BeautifulSoup:超过24个字符(从a到z)的迭代失败:降低了首次深入了解数据集的复杂性:

如何将泛型类类型与函数返回类型结合使用?