我有一列带有一些字符串值的pandas列:

White bear
Brown Bear
Brown Bear 100 Kg
White bear 200 cm


如何检查所有字符串是否包含序列“ White bear”并将整个值(不仅是序列)替换为“ White_bear”之类的字符串?

df['Species'] = df['Species'].str.replace('White bear', 'White_bear')


不适用于我,因为它仅替换了序列。

最佳答案

您可以使用布尔索引:

In [173]: df.loc[df.Species.str.contains(r'\bWhite\s+bear\b'), 'Species'] = 'White_bear'

In [174]: df
Out[174]:
             Species
0         White_bear
1         Brown Bear
2  Brown Bear 100 Kg
3         White_bear


或更一般的解决方案:

In [204]: df
Out[204]:
             Species
0         White bear
1         Brown Bear
2  Brown Bear 100 Kg
3  White bear 200 cm

In [205]: from_re = [r'.*?\bwhite\b\s+\bbear\b.*',r'.*?\bbrown\b\s+\bbear\b.*']

In [206]: to_re = ['White_bear','Brown_bear']

In [207]: df.Species = df.Species.str.lower().replace(from_re, to_re, regex=True)

In [208]: df
Out[208]:
      Species
0  White_bear
1  Brown_bear
2  Brown_bear
3  White_bear


RegEx explanation

关于python - 用 Pandas 替换字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40319746/

10-10 13:28