【问题标题】:Extracting all 10 digit numbers from a data frame entry (text) [closed]从数据框条目中提取所有 10 位数字(文本)[关闭]
【发布时间】:2021-07-25 10:40:21
【问题描述】:

我有一个 pandas 数据框,其中只有一列包含文本(单词和数字)。 我想从文本中提取所有 10 位数字,但无法将 pd.series 对象转换为像列表这样的可迭代对象。

我尝试了类似的方法:

def find_number(text):
    num = re.findall(r'[0-9]+',text)
    return " ".join(num)

df['List1']=df['Header 1'].apply(lambda x: find_number(x))

但这仍然给了我一个不可迭代的对象。

提前致谢

【问题讨论】:

  • 删除" ".join()?
  • @Guy 为什么? findall 返回字符串列表。这不是问题所在
  • @DeepSpace 据我了解,OP 想要一个列表,而是获取一个字符串。
  • max 请提供minimal reproducible example 并查看How to Ask 您需要提供一个模拟您的解决方案以及您的预期输出的示例。这是在互联网上向善良的陌生人寻求帮助时的最低要求
  • 嗨,很抱歉让它有点复杂。这是我第一次在这里发帖。我必须重新阅读发布指南。您的帮助令人惊叹,非常感谢。 Exapmle 在数据帧的每一行中看起来像这样:“apibdnvcponsdvcopn üiounasdcopnqdc 07082021 owidcnqüwoeic number one 1234567890 number two 0987654321” 我只想在其中包含可迭代的 1234567890 和 0987654321。非常感谢大家

标签: python pandas dataframe object


【解决方案1】:

将正则表达式从 '[0-9]+' 更改为 '\d{10}' 以仅获得 10 位数字的结果并删除 " ".join() 以将结果保留为列表

def find_number(text):
    return re.findall(r'\d{10}', text)

df['List1'] = df['Header 1'].apply(lambda x: find_number(x))
# or without separate function
df['List1'] = df['Header 1'].apply(lambda x: re.findall(r'\d{10}', x))


print(df['Header 1'])
# 0    apibdnvcponsdvcopn üiounasdcopnqdc 07082021 owidcnqüwoeic number one 1234567890 number two 0987654321
# 0    Name: Header 1, dtype: object

print(df['List1'])
# 0    [1234567890, 0987654321]
#      Name: List1, dtype: object

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多