how to remove leading extra space for each row when pandata datafarme is converted to_string

Viewed 31

I have a pandas dataframe which I am trying to convert to string using newdf= old_df.to_string(index=False). After this step automatically spaces are being added to the first 2 row's. Any suggessions how to remove that?

old_df:

column_name
row1
row2
row3

newdf:

    row1
    row2
row3

If I do newdf=newdf.lstrip(' ') then the space at first row is removed but space at 2nd row remains as it is

newdf:

row1
    row2
row3
1 Answers

If you use the .toString(index=False) you will always have that problem. So if you want to fix the spacing issue just use .toString().

Like this:

import numpy as np
import pandas as pd
d = {'c1': [2, 3, 4], 'c2': [5, 6, 7]}
df = pd.DataFrame(d)
newdf= df.to_string()
print(newdf)
Related