gpt4 book ai didi

python - Pandas 正则表达式返回任何包含 U 或 UN 的字符串和数字

转载 作者:行者123 更新时间:2023-12-04 10:28:50 25 4
gpt4 key购买 nike

我正在尝试使用另一个列字符串中的值创建一个新列
我想要的是创建一个带有单位值的新列。

单元的位置可以变化。

我的字符串的例子是

this is a string and we have 4U to use
this is another string 5UN
only 6U to use today

由于位置不同,我需要提取连接到 U 和 UN 的数字。
df['test_units'] = df['ITEM_DESC'].str.get(r'\(*U.*?\)',)
df['test_units']

这是我的正则表达式,但我只返回 nan 值。

我如何只返回加入 U 或 UN 的号码?

最佳答案

您可以使用

df['test_units'] = df['ITEM_DESC'].str.extract(r'\b(\d+)UN?\b')

regex demo .请注意形成捕获组的未转义括号对,其值由 Series.str.extract 返回。 .

正则表达式匹配:
  • \b - 一个词边界
  • (\d+) - 第 1 组:一位或多位数字
  • U - U
  • N? - 可选 N
  • \b - 字边界

  • Pandas 测试:
    import pandas as pd
    cols={'ITEM_DESC': ['this is a string and we have 4U to use','this is another string 5UN','only 6U to use today']}
    df = pd.DataFrame(cols)
    df['test_units'] = df['ITEM_DESC'].str.extract(r'\b(\d+)UN?\b')

    输出:
    >>> df
    ITEM_DESC test_units
    0 this is a string and we have 4U to use 4
    1 this is another string 5UN 5
    2 only 6U to use today 6
    >>>

    关于python - Pandas 正则表达式返回任何包含 U 或 UN 的字符串和数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60503893/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com