簡體   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