Search code examples
pythonpandasdataframeformattingseparator

Format Pandas columns with thousand space separator


I tried to look everywhere, but there is no exact answer to what I'm looking for.

I know the standard formatting for a thousand is with a comma, but I want a space as a thousand separator. I tried this solution, but there is still the comma as a separator:

d = {'col1': [1000, 20000], 'col2': [300000, 400000]}
df=pd.DataFrame(d)
df['col1']=df['col1'].map('{:,.0f}'.format)
df['col1'].astype(str)
df['col1'].replace(',',' ',inplace=True)

Solution

  • You need to assign the work done to the variable, for example df['col1'].astype('str') needs to be assigned to df['col1']

    Try this

    d = {'col1': [1000, 20000], 'col2': [300000, 400000]}
    df = pd.DataFrame(d)
    for col in df.columns:
        df[col] = df[col].map('{:,.0f}'.format)
        df[col] = df[col].astype('str')
        df[col] = df[col].str.replace(',',' ')
    print(df)
    

    output

         col1     col2
    0   1 000  300 000
    1  20 000  400 000