【问题标题】:Python- How to update column by taking substring from another column?Python-如何通过从另一列获取子字符串来更新列?
【发布时间】:2016-07-26 03:26:39
【问题描述】:

我有一个如下所示的列表: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 错误。

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

【问题讨论】:

  • 如果“你有长发还是短发”怎么办? col3 应该包含什么以及为什么?
  • 两个都去掉,先保留。我会更新问题
  • @Alexander 我确信这不会在我使用的数据集中发生。但是,就我的目的而言,取第一个值就足够了

标签: python python-3.x pandas dataframe python-3.5


【解决方案1】:

创建示例数据框:

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 表达式与 reduce 一起使用以从 col2 中删除每个匹配的单词:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 2021-08-09
    • 2022-11-15
    • 2018-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多