[英]replace '()' from a dataframe pandas python
I have a dataframe and it contains some values like我有一个 dataframe 它包含一些值,例如
the change (♠)
and the new (⦻)
my desired output is我想要的 output 是
the change
and the new
I have tried to use我试过用
df.columns = df.columns.str.strip(' ()')
df=df.replace('\()','',regex=False)
but nothing worked, can anyone help?但没有任何效果,有人可以帮忙吗? Thanks谢谢
If you have dataframe:如果您有 dataframe:
col1 col2
0 value1 the change ()
1 the change () value3
2 value2 value4
3 () other change NaN
You can replace the ()
in whole dataframe:您可以替换整个dataframe 中的()
:
df = df.apply(lambda x: x.str.replace(r"\s*\(\)\s*", "", regex=True))
print(df)
Prints:印刷:
col1 col2
0 value1 the change
1 the change value3
2 value2 value4
3 other change NaN
EDIT: If you have df:编辑:如果你有 df:
col1 col2
0 value1 the change (♠)
1 the change (⦻) value3
2 value2 value4
3 () other change NaN
Then:然后:
df = df.apply(lambda x: x.str.replace(r"\s*\(.*?\)\s*", "", regex=True))
print(df)
Prints:印刷:
col1 col2
0 value1 the change
1 the change value3
2 value2 value4
3 other change NaN
You have almost done it.你几乎做到了。 Just change regex = True
in your code and modify the regex to remove the spaces as well.只需在代码中更改regex = True
并修改正则表达式以删除空格。
Input dataset输入数据集
col1 col2
0 change () val1
1 val2 samplestring ()
2 change 2() val 5()
df.replace(r'\s*\(\s*\)\s*', '', regex = True, inplace = True)
Output dataset: Output 数据集:
col1 col2
0 change val1
1 val2 samplestring
2 change 2 val 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.