Search code examples
pythonstringreplacestripspaces

Python Strip ALL Spaces from DataFrame String Field


I have a Dataframe with the following column:

enter image description here

I am trying to remove all spaces (leading, trailing, and in-between). For example, 'Low Potential' should show as 'LowPotential'. I have tried the following code but it did not appear to work:

df_merged_1['Priority Type'] = df_merged_1['Priority Type'].replace(' ', '')

Any help is greatly appreciated!


Solution

  • You can use str.replace method; The Series.replace method is meant to replace values literally (exact match), i.e, replace a value which is a whitespace in the series instead of stripping the white space from the string:

    df_merged_1['Priority Type'] = df_merged_1['Priority Type'].str.replace(' ', '')
    

    Alternatively, you can specify regex=True in the replace method:

    df_merged_1['Priority Type'] = df_merged_1['Priority Type'].replace(' ', '', regex=True)