代码之家  ›  专栏  ›  技术社区  ›  Crystal

如何使用st.contains将文本从旧列移动到新创建的列

  •  0
  • Crystal  · 技术社区  · 4 年前

    我想根据python中的关键字将描述文本列移动到新创建的列。

    例如,如果关键字是“Table”、“Fan”、“Chair”

    Description(Given)       Keyword Table        Keyword Fan        Keyword Chair
    
    The table is long        The table is long
    The fan is nice                               The fan is nice
    The fan is cheap                              The fan is cheap
    The chair is brown                                               The chair is brown 
    
    

    我试图同时使用str.contains()和str.findall(),但它要么给出T | F布尔值,要么只给出关键字(例如“chair”)

    df['Keyword Table'] = df['Description'].str.contains('Table')
    

    keywords=['Table']
    df['Keyword Table'] = df['Description'].str.findall((keywords)).apply(set)
    
    3 回复  |  直到 4 年前
        1
  •  1
  •   mozway    4 年前

    下面是一种使用带有命名捕获组的正则表达式的简单方法:

    df = pd.DataFrame({'Desc': ['The table is long', 'The fan is nice', 'The fan is cheap', 'The chair is brown']})
    words = ['table', 'fan', 'chair']
    
    regex = '|'.join(f'(?P<{w}>.*{w}.*)' for w in words)
    df.join(df['Desc'].str.extract(regex, expand=False).add_prefix('keyword_'))
    

    注意。命名的捕获组不能有特殊字符或空格。如果是这种情况,请告诉我,并且可以更改捕获组的名称。 输出:

                     Desc      keyword_table       keyword_fan       keyword_chair
    0   The table is long  The table is long               NaN                 NaN
    1     The fan is nice                NaN   The fan is nice                 NaN
    2    The fan is cheap                NaN  The fan is cheap                 NaN
    3  The chair is brown                NaN               NaN  The chair is brown
    

    其他选择 get_dummies

    df = pd.DataFrame({'Desc': ['The table is long', 'The fan is nice', 'The fan is cheap', 'The chair is brown']})
    words = ['table', 'fan', 'chair']
    
    regex = '(%s)' % '|'.join(words)
    df.join(pd.get_dummies(df['Desc'].str.extract(regex, expand=False))
              .mul(df['Desc'], axis=0)
              .add_prefix('keyword_')
            )
    
        2
  •  0
  •   Anynamer    4 年前

    您的布尔数列可以用作索引来分割数据帧,如下所示:

    df['Keyword Table'] = df[df['Description'].str.contains('Table', na = False)]['Description']
    

    要查看关键字列表,可以使用apply:

    keywords = ['Table', 'Fan', 'Chair']
    
    df['Keywords'] = df[df['Description'].apply(lambda x: any(k in x for k in keywords))]['Description']
    
        3
  •  0
  •   Klaus78    4 年前

    这段代码有用吗?

    df = pd.DataFrame({'Desc':['cat is black','dog is white']})
    kw = ['cat','dog']
    for k in kw:
       df[k + ' col'] = df.Desc.map(lambda s: s if k in s else '' )
    

    输出是

    enter image description here