Home > OS >  Pandas not replacing the string correctly
Pandas not replacing the string correctly

Time:12-18

This my pandas dataframe:

print(top)

Result:

Countries Population
China[B] 1376
India 1200

I want to remove the '[B]' from China, and for that, I ran the following code:

top['Countries'] = top['Countries'].str.replace('[B]', '')

But the result was unsatasfying:

Countries Population
China[] 1376
India 1200

I also received the following warning:

C:\Users\walde\AppData\Local\Temp/ipykernel_8068/4262663465.py:1: FutureWarning: The default value of regex will change from True to False in a future version.

What´s wrong here?

CodePudding user response:

'[B]' is treated as a regular expression, which in this case means all characters within the brackets will be replaced (which is just B).

Use regex=False.

  • Related