用df.mask掩盖某些材料

2024-09-27 23:17:02 发布

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

我试图弄清楚是否可以将df.mask用于某些事情,例如,我的数据帧如下所示:

          col1                    col2
1     name1(colonel)         name1(colonel)
2     name2(colonel)         name1(colonel)
3     name3(colonel)         name1(colonel)

我想使用df.mask来覆盖(collone)部分,而不使用名称,这样我得到的数据帧就会像这样

col1       col2

name1      name1
name2      name2
name3      name3

但我似乎不能用df.mask做那至少我找不到一个方法去做我想做的


Tags: 数据方法名称dfmask事情col2col1
1条回答
网友
1楼 · 发布于 2024-09-27 23:17:02

看起来您需要数据帧上的replace方法,它可以在regex模式下使用。模式\\(.*\\)可用于匹配由一对圆括号括起来的内容,圆括号可替换为空字符串(以删除它)。如果您不熟悉正则表达式,请对其进行一点分解:

  • \\(匹配左括号
  • .匹配任何字符
  • *是量词,表示0或更多
  • \\)匹配右括号

组合在一起,它匹配由一对括号括起的任何字符串(包括:

df.replace("\\(.*\\)", "", regex=True)

enter image description here

相关问题 更多 >

    热门问题