Home > OS >  Convert float64 to string with 2 decimal
Convert float64 to string with 2 decimal

Time:08-17

I have a column of data and I am trying to push to 2 decimal places from the data to get 73.35 35.72 35.51 etc.

It currently looks like this when I read the excel file into python.

0              NaN
1              NaN
2              NaN
3              NaN
4              NaN
           ...    
49056    73.345000  
49057    35.720833
49058    35.505000  
49059    17.075000  
49060    27.710000
Name: AMOUNT, Length: 49061, dtype: object

I am using

pd.to_numeric(df['PAYMENT']).fillna(0).astype(str).mask(df['PAYMENT'].isnull())

But only get this

0              NaN
1              NaN
2              NaN
3              NaN
4              NaN
           ...    
49056       73.345
49057    35.720833
49058       35.505
49059       17.075
49060        27.71
Name: AMOUNT, Length: 49061, dtype: object

Any help is appreciated!

CodePudding user response:

df['PAYMENT'].round(2).astype(str)

round() converts the number to two decimal places, then you can do astype(str) to convert it to a string. Not sure really why you need it to be a string though

CodePudding user response:

Two ideas:

  • Do you have values >= 1000? Excel might write them as 1,234.567
  • To round your values to 2 decimals use .round(2), e.g. df['PAYMENT'].astype(float).fillna(0).round(2)
  • Related