当另一列包含此子字符串时,使用Pandas删除列中字符串的子字符串

2024-04-18 17:56:30 发布

您现在位置:Python中文网/ 问答频道 /正文

此框架中的熊猫数据:

df = pd.DataFrame({'a': ['foo_abc', 'bar_def', 'ghi'], 'b': ['foo', 'bar', 'yah']})

    a               b
0   foo_abc         foo
1   bar_def         bar
2   ghi             yah

我想,可能使用regex,从a列的字符串中删除b列中的字符串以生成

^{2}$

我怎么能对熊猫这么做呢?在


Tags: 数据字符串框架dataframedffoodefbar
1条回答
网友
1楼 · 发布于 2024-04-18 17:56:30

在列表理解中使用replacestrip

df['c'] = [a.replace(b, '').strip('_') for a, b in zip(df['a'], df['b'])]
print (df)
         a    b    c
0  foo_abc  foo  abc
1  bar_def  bar  def
2      ghi  yah  ghi

含有re.sub的溶液:

^{pr2}$

相关问题 更多 >