Pandas str.extract for np.where: 正则表达式捕获组外的空格会抛出 AttributeEr



从这两个字符串中,我想捕获第一行中说5X的部分,而不是第二行中X50的部分:

    "name"
1   LONG YOX 5X AAA
2   LONG YOX50 AAA

对于pandas.DataFrame.loc操作,我使用 numpy.where 作为定位器提取上述部分,long_keyword str.extract用于正则表达式:

long_keyword = df.loc[df["name"].str.contains("LONG", case=False), "name"]
df.loc[df["name"].str.contains(long_keyword, case=False), "result_column"] = np.where(long_keyword.str.extract(r"s(d+X|Xd+)", flags=re.IGNORECASE).str.strip("Xx").str.isdigit(), "+" + long_keyword.str.extract(r"s(d+X|Xd+)", flags=re.IGNORECASE).str.strip("Xx") + "00", "+100")

当我使用正则表达式s(d+X|Xd+)时,我得到:

AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas

但是当我使用相同的正则表达式而不使用前导空格时,s捕获组之外 - 即 (d+X|Xd+) – 我没有收到任何错误。但是,这意味着我不想要的字符串部分将包含在捕获中。

问:如何修复此错误?问题是空格s还是我在捕获组()之外有正则表达式标识符?

假设你有一个这样的文件

10,"ABC YOX 5X AAA"
20,"ABC YOX50 AAA"

因此,数据框如下所示

           string
10  ABC YOX 5X AAA
20   ABC YOX50 AAA

你想要这个吗?

df['size']=df['string'].apply(lambda x: len(x.split()))
df['interest']=df[df['size']==4]['string'].str.split(" ").str.get(2)

输出

           string  size interest
10  ABC YOX 5X AAA     4       5X
20   ABC YOX50 AAA     3      NaN

这是你想要的吗?

最新更新