Python- 如何通过从另一列中获取子字符串来更新列?

Python- How to update column by taking substring from another column?

我有一个如下所示的列表:li = ['ShortHair','LongHair','Medium Hair']

我想检查 col2 是否包含上述任何子字符串,如果它确实从 col2 中获取并更新 col3。如果没有,则保持 col3 不变。

     col1   col2               col3
0       w   I have ShortHair      U
1       x   LongHair You Have     V
2       y   I have no hair        W
3       z   Look Medium Hair!     L

获得:

     col1   col2               col3
0       w   I have             ShortHair
1       x   You Have           LongHair
2       y   I have no hair        W
3       z   Look !             Medium Hair

编辑: 如果数组中多次出现子字符串,则删除两个表单 col2 并用第一个值更新 col3。

我可以从 col2 中删除子字符串,但是我无法更新 col3。我试过了:

data[data.col2.str.contains('|'.join(li)),"col3"] = data["col2"].map(lambda x: re.findall('|'.join(li),x)[0])

它给出 IndexError: list index out of range 错误。

我怎样才能最好地做到这一点?

创建示例数据框:

df = pd.DataFrame(
    {'col1': ['w', 'x', 'y', 'z'],
     'col2': ['I have ShortHair', 'LongHair You Have', 'I have no hair', 'Look Medium Hair!'],
     'col3': ['U', 'V', 'W', 'L']})

使用带有列表理解的 lambda 表达式来查找每行中的所有匹配词。这是一个临时列,稍后将被删除。

df['matches'] = df.col2.apply(lambda sentence: [word for word in li if word in sentence])

为包含匹配词的行创建掩码。

mask = df.matches.apply(len) > 0

使用掩码和 .loc,用第一个匹配词更新 col3

df.loc[mask, 'col3'] = df.loc[mask, 'matches'].str[0]

使用 lambda 表达式和 reducecol2 中删除每个匹配的词:

df.loc[mask, 'col2'] = (
    df.loc[mask, 'col2'].apply(lambda sentence: 
                               reduce(lambda remaining_sentence, word: 
                                      remaining_sentence.replace(word, ''), li, sentence)))

删除匹配词的临时列。

del df['matches']

确认结果。

>>> df
  col1            col2         col3
0    w         I have     ShortHair
1    x        You Have     LongHair
2    y  I have no hair            W
3    z          Look !  Medium Hair