Home > other >  Display the first decimal point number Pandas
Display the first decimal point number Pandas

Time:07-06

I have this Day to Year & Month conversion and I implement them into pandas dataframe

import numpy as np
import math
import matplotlib.pyplot as plt 
import pandas as pd 

day_len = math.floor((np.random.randint(0,100))/2)
if day_len != 0:    
    day = [i for i in (np.random.randint(1,1000,day_len))]
else:
    pass

data = pd.DataFrame({'Day': day})
data['Year'] = data['Day'].apply(lambda x: (x/365))
data['Month'] = data['Day'].apply(lambda r: math.floor((r*0.032855)))

data

This is the output:

Day      Year      Month
0   419  1.147945   13
1   453  1.241096   14
2   421  1.153425   13
3   448  1.227397   14
4   638  1.747945   20
5   13   0.035616   0
6   769  2.106849   25
7   367  1.005479   12
8   318  0.871233   10

For the Year column, I want the values to display the only first integer from the left side and the first decimal point integer, example of output I wanted:

   Year
    1.1
    1.2
    1.5
    2.1

How do I write a code that construct what I wanted from the example above?

CodePudding user response:

You can try

df['Year'] = df['Year'].round(1)
   Day  Year  Month
0  419   1.1     13
1  453   1.2     14
2  421   1.2     13
3  448   1.2     14
4  638   1.7     20
5   13   0.0      0
6  769   2.1     25
7  367   1.0     12
8  318   0.9     10
  • Related