Search code examples
pythonscikit-learnfloating-pointpredictsklearn-pandas

I want to 2 decimal points result for predicts on Python


My outputs have too much decimal points. But I want to 2 points float results. Can you help me?

EX: 42.44468745 -> 42.44

y_pred=ml.predict(x_test)
print(y_pred)

Output:

[42.44468745 18.38280575  7.75539511 19.05326276 11.87002186 26.89180941
 18.97589775 22.01291508  9.08079557  6.72623692 21.81657224 22.51415263
 24.46456776 13.75392096 21.57583275 25.73401908 30.95880457 11.38970094
  7.28188274 21.98202474 17.24708345 38.7390475  12.68345506 11.2247757
  5.32814356 10.41623796  7.30681434]

Solution

  • Since you didn't post all of your code, I can only give you a general answer.

    There are several ways to get two decimals.

    For example:

    num = 1.223362719
    
    print('{:.2f}'.format(num))
    
    print('%.2f' % num)
    
    print(round(num, 2))
    
    print(f"{num:.2f}")
    

    You will get 1.22 as the result of any of these.

    ------------------Update------------------

    Thanks for commenting, and I have updated to deal with your problem.

    Using numpy could help you when your data OP is using an ndarray.

    You can use data= np.around(a, n) # a is the data that needs to be decimal processed, and n is the reserved number.

    Example:

        import numpy as np
        data= np.around(1.223362719, 2) 
    

    You will also get 1.22 as the result.