简体   繁体   English

使用 for 循环从 pandas dataframe 列中删除字符

[英]Removing a char from a pandas dataframe column with for loop

I have a DF that has a country column and some of that countries has "(" in it. I tried to remove all of that "(" s with this for loop:我有一个包含国家/地区列的 DF,其中一些国家/地区中有“(”。我试图用这个 for 循环删除所有“(”):

for country in df_energy['Country']:
    if ')' in df_energy['Country']:
        df_energy['Country'] = df_energy['Country'].replace({'(':'', ')':''})

But when I print that DF again, I see all parenthesis did not removed.但是当我再次打印那个 DF 时,我看到所有括号都没有被删除。 I'd be happy if someone say where I made a mistake.如果有人说我在哪里犯了错误,我会很高兴。

Thanks.谢谢。

You don't need the loop:你不需要循环:

df_energy['Country'] = df_energy['Country'].str.replace('[()]', '')

If you want to only replace matching () then:如果您只想替换匹配的()则:

df_energy['Country'] = df_energy['Country'].str.replace('\((.*)\)', r'\1')

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

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