【问题标题】:Show the first string from a list of strings that appears in a column of strings显示出现在字符串列中的字符串列表中的第一个字符串
【发布时间】:2021-06-07 12:57:05
【问题描述】:

我有一个颜色数据框df 和一个参考颜色列表look_for

df = pd.DataFrame({'colour': ['Black12', 'White', 'WhiteBlack', 'RedWhite', 'RedGreen', 'Yellow']})
look_for = ['White', 'Black', 'Red', 'Green']

我正在尝试创建一个列colour2,使其代表look_for 中出现在每行字符串中的第一个单词。由于我的数据框有 200 多个颜色条目,而我的参考列表有 500 多个颜色条目,因此什么是一种省时的方法。

我想要的输出是:

Out[0]: 
       colour colour2
0     Black12   Black
1       White   White
2  WhiteBlack   White
3    RedWhite   White
4    RedGreen     Red
5      Yellow    None

谢谢。

【问题讨论】:

    标签: python pandas string


    【解决方案1】:

    您可以尝试使用apply 和自定义函数来检查列表中的每个项目,如果它是给定字符串值的子字符串,则立即返回该值,它会相当快。

    def getString(value):
        for item in look_for:
            if item in value:
                return item
    
    df['colour2'] = df['colour'].apply(getString)
    

    输出

           colour color2
    0     Black12  Black
    1       White  White
    2  WhiteBlack  White
    3    RedWhite  White
    4    RedGreen    Red
    5      Yellow   None
    

    快速比较:

    Iteration:  0
    Avergae time for 1000 iteration with str.extract: 0.00060 seconds
    Avergae time for 1000 iteration with str.findall: 0.00296 seconds
    Avergae time for 1000 iteration with custom function and apply: 0.00046 seconds
    ---------------------
    Iteration:  1
    Avergae time for 1000 iteration with str.extract: 0.00055 seconds
    Avergae time for 1000 iteration with str.findall: 0.00272 seconds
    Avergae time for 1000 iteration with custom function and apply: 0.00051 seconds
    ---------------------
    Iteration:  2
    Avergae time for 1000 iteration with str.extract: 0.00056 seconds
    Avergae time for 1000 iteration with str.findall: 0.00265 seconds
    Avergae time for 1000 iteration with custom function and apply: 0.00056 seconds
    ---------------------
    Iteration:  3
    Avergae time for 1000 iteration with str.extract: 0.00069 seconds
    Avergae time for 1000 iteration with str.findall: 0.00269 seconds
    Avergae time for 1000 iteration with custom function and apply: 0.00045 seconds
    ---------------------
    Iteration:  4
    Avergae time for 1000 iteration with str.extract: 0.00053 seconds
    Avergae time for 1000 iteration with str.findall: 0.00265 seconds
    Avergae time for 1000 iteration with custom function and apply: 0.00051 seconds
    ---------------------
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-24
      • 2012-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多