繁体   English   中英

从 dataframe pandas python 替换“()”

[英]replace '()' from a dataframe pandas python

我有一个 dataframe 它包含一些值,例如

the change (♠)
and the new (⦻)

我想要的 output 是

the change
and the new

我试过用

df.columns = df.columns.str.strip(' ()')
df=df.replace('\()','',regex=False)

但没有任何效果,有人可以帮忙吗? 谢谢

如果您有 dataframe:

              col1           col2
0           value1  the change ()
1    the change ()         value3
2           value2         value4
3  () other change            NaN

您可以替换整个dataframe 中的()

df = df.apply(lambda x: x.str.replace(r"\s*\(\)\s*", "", regex=True))
print(df)

印刷:

           col1        col2
0        value1  the change
1    the change      value3
2        value2      value4
3  other change         NaN

编辑:如果你有 df:

              col1            col2
0           value1  the change (♠)
1   the change (⦻)          value3
2           value2          value4
3  () other change             NaN

然后:

df = df.apply(lambda x: x.str.replace(r"\s*\(.*?\)\s*", "", regex=True))
print(df)

印刷:

           col1        col2
0        value1  the change
1    the change      value3
2        value2      value4
3  other change         NaN

你几乎做到了。 只需在代码中更改regex = True并修改正则表达式以删除空格。

输入数据集

         col1             col2
0   change ()             val1
1        val2  samplestring ()
2  change 2()          val 5()
df.replace(r'\s*\(\s*\)\s*', '', regex = True, inplace = True)

Output 数据集:

       col1          col2
0    change          val1
1      val2  samplestring
2  change 2         val 5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM