【问题标题】:Extract specific value from the string column of a Pandas Data frame从 Pandas 数据框的字符串列中提取特定值
【发布时间】:2021-07-10 18:27:06
【问题描述】:

我是 Python 新手。我从通过 Excel 工作表的插件中获取数据,我需要从该列中提取值。

  Plugin Output

 Country:USA   State: Virginia Address: 23 xys lane  SSN:2345550404  Zip : 22102 City: Fairfax

 Country:India State:Virginia  SSN:2345550401  ZIP:452002  City: Indore

我需要在每一行中搜索 SSN 并在新的 pandas 数据框中创建一个新列以创建一个单独的列。

期望的输出:

  SSN

 2345550404

 2345550401

序列号答案:

def find_serialnumber(x):
  num = re.findall(r'Serial Number:\s*([^\n]+)', x)
  return " ".join(num)

【问题讨论】:

  • 您能否编辑您的问题并格式化输入和预期输出(Ctrl+K 格式化为代码)。
  • 您好,欢迎您。如果您可以查看how-to-ask,然后尝试生成mcve,那就太好了。

标签: python pandas


【解决方案1】:
import re

    def find_number(x):
        num = re.findall(r'(?:SSN_)(\d+)', x)
        return " ".join(num)

    df['SSN'] =df['Output'].apply(lambda x: find_number(x))

同样从 pandas 中提取函数:

所以 \d+ 表示匹配 1 个或多个数字。

df['SSN'] = df['Output'].apply(lambda x: re.findall(r'(?:SSN_)(\d+)', x)[0] if re.findall(r'(?:SSN_)(\d+)', x) else x)

【讨论】:

  • 感谢 Piotr Zak。如果需要查找的另一列是序列号:00 DB C0 B1 E3 D5 05 7B 57 BE 3A BB FF D1 62 D6 A7
  • 您可以使用 apply(lambda) 重用该函数 - 但应用另一个正则表达式。
  • 你能帮我用正则表达式吗?
  • 是的 - 明天 - 现在我建议在 Google 上搜索 :)
  • 真的吗?我可以稍后看看
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-24
  • 1970-01-01
  • 2022-10-07
  • 1970-01-01
  • 2021-05-26
相关资源
最近更新 更多