Home > Software engineering >  Remove spaces from strings in pandas DataFrame not working
Remove spaces from strings in pandas DataFrame not working

Time:01-04

Trying to remove spaces from a column of strings in pandas dataframe. Successfully did it using this method in other section of code.

for index, row in summ.iterrows():
    row['TeamName'] = row['TeamName'].replace(" ", "")

summ.head() shows no change made to the column of strings after this operation, however no error as well.

I have no idea why this issue is happening considering I used this exact same method later in the code and accomplished the task successfully.

CodePudding user response:

Why not use str.replace:

df["TeamName"] = df["TeamName"].str.replace(r' ', '', regex=False)

CodePudding user response:

I may be proven wrong here, but I am wondering if its because you are iterating over it, and maybe working on a copy that isn't changing the data. From pandas.DataFrame.iterrows documentation, this is what I found there:

"You should never modify something you are iterating over. This is not guaranteed to work in all cases. Depending on the data types, the iterator returns a copy and not a view, and writing to it will have no effect."

just a thought... hth

  • Related