繁体   English   中英

根据 pandas dataframe 列中字符串的开头应用列表中的字符串

[英]Apply string in list according to beginning of the strings in a pandas dataframe column

让我们举个例子。

我有一个已识别的类别列表:

L_known_categories = ["Orange","Green","Red","Black & White"]

该列表中的字符串不能是该列表中另一个字符串的 substring。

还有一个 dataframe:

df = pd.DataFrame({"Items":["green apple","blue bottle","RED APPLE","Green paper","Black & White glasses",
                            "An orange fruit"]})

                   Items
0            green apple
1            blue bottle
2              RED APPLE
3            Green paper
4  Black & White glasses
5        An orange fruit

我想在此 dataframe 中添加一列Category 如果Items列中的字符串以L_known_categories中的字符串开头,则无论字符的大小写如何,类别都是该字符串。 如果没有创建字符串,则类别是列Items中的字符串。

我可以使用 for 循环,但对于我真正的大 dataframe 来说效率不高。 请问我该怎么办?

预期 output:

                   Items         Category
0            green apple            Green
1            blue bottle      blue bottle
2              RED APPLE              Red
3            Green paper            Green
4  Black & White glasses    Black & White
5        An orange fruit  An orange fruit

您可以在pandas.Series.str.extract中使用regex

>>> df['Category'] = df['Items'].str.title().str.extract(
        '(^' 
        + '|'.join(L_known_categories) 
        + ')'
    )[0].fillna(df['Items'])

>>> df
    Items                   Category
0   green apple             Green
1   blue bottle             blue bottle
2   RED APPLE               Red
3   Green paper             Green
4   Black & White glasses   Black & White
5   An orange fruit         An orange fruit

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM