Search code examples
pythonpandasdataframedecimalrounding

Change a single float number in Data frame


I'm almost done with my assignment. However, I have to make only one small adjustment to my final data frame. For the column "CL_Total" the first row number 157.580 has be changed to two decimals, not three. I only have to change this number. Can anybody help me?

enter image description here

The Data frame should look like this: enter image description here

The code I have now is this, but the number does not change in two decimals:

df_final['CL_total'].iloc[0] == df_final['CL_total'].iloc[0].round(2)
print(df_final.iloc[:6])

Solution

  • That column of your dataframe contains floats, and 157.850 and 157.85 are the same float. As far as I know, pandas will always show the same number of decimal places for all the values in a column of floats. If you want to manipulate the number of trailing zeroes like that, you'll need to convert the number to a strings:

    >>> df = pd.DataFrame({'values': [15.58, 12.345]})
    >>> print(df)
       values
    0  15.580
    1  12.345
    >>> df['values'].iloc[0] = str(df['values'].iloc[0].round(2))
    >>> print(df)
      values
    0  15.58
    1 12.345
    

    A pandas dataframe is really a store of data, not a visual product like a spreadsheet. So if you want to get a dataframe in shape to be used that way, converting things to strings is a good idea.