Remove spaces from strings in pandas DataFrame not working

Question:

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.

Asked By: sfarls

||

Answers:

Why not use str.replace:

df["TeamName"] = df["TeamName"].str.replace(r' ', '', regex=False)
Answered By: Tim Biegeleisen

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

Answered By: Jimbo