Search code examples
pythonlistdataframeroundingtolist

How to convert dataframe to list without adding more decimal places in python


I have a dataframe. The values are 5 decimal places as shown in the first image.

After I use df.values.tolist() to convert to list, some became more than 5 decimal places as shown the 2nd image.

How can I convert to list and keep the original decimal places? I don't want to use loop and round them after because I have over 30 million rows and it takes too much time. Thanks.

enter image description here enter image description here


Solution

  • Have you tried rounding the df first and then converting to list

    df[numeric_columns] = df[numeric_columns].round(5)
    df = pd.concat([df[non_numeric_columns], df[numeric_columns]]), axis=1)
    

    Then

    df.values.tolist()