Setting number of decimals in dataframe for a calculated value

Viewed 2832

I would like to set the precision of the mean value in a dataframe, but I get the following error: TypeError: cannot convert the series to <class 'float'>

I set the arrays as dtype=float. It works if I remove "%.2f"%, but gives more decimal points than I want.

Following is the code:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.array([[0, 0.030, 0.031, 0.032], [10, 0.153, 0.155, 0.154], [20, 0.393, 0.397, 0.395]]), columns=['Y0','Y1', 'Y2', 'Y3'], dtype=float)
Xa=df.loc[:,"Y1":]
mean=Xa.mean(axis=1)
df['mean']="%.2f"%mean
df
5 Answers
  • In your implementation, df['mean'] = "%.2f"%mean causes a TypeError because mean is pandas.Series, which can't be converted with "%.2f"%mean.
    • Use df['mean'] = mean.round(3).
    • Use pandas.Series.round to round pandas.Series to the desired decimal place, and retain a float type.
  • Use pandas.DataFrame.mean with axis=1 to return the mean for all of the rows, and assign the values to a new column.
  • Use pandas.DataFrame.round to round an entire dataframe (e.g. Xa.round(3).
import pandas as pd
import numpy as np

# test dataframe
df = pd.DataFrame(np.array([[0, 0.030, 0.031, 0.032], [10, 0.153, 0.155, 0.154], [20, 0.393, 0.397, 0.395]]), columns=['Y0', 'Y1', 'Y2', 'Y3'], dtype=float)

# select the desired columns
Xa = df.loc[:,"Y1":]

# get the column means and round them
Xa['means'] = Xa.mean(axis=1).round(3)

# display(Xa)
      Y1     Y2     Y3  means
0  0.030  0.031  0.032  0.031
1  0.153  0.155  0.154  0.154
2  0.393  0.397  0.395  0.395

How about just using the round function?

mean=round(Xa.mean(axis=1),2)

You can try using the map function:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.array([[0, 0.030, 0.031, 0.032], [10, 0.153, 0.155, 0.154], [20, 0.393, 0.397, 0.395]]), columns=['Y0','Y1', 'Y2', 'Y3'], dtype=float)
Xa=df.loc[:,"Y1":]
mean=Xa.mean(axis=1)
df['mean']=mean.map(lambda x: '%.2f' % x)
df

Output:

    Y0      Y1      Y2      Y3      mean
0   0.0     0.030   0.031   0.032   0.03
1   10.0    0.153   0.155   0.154   0.15
2   20.0    0.393   0.397   0.395   0.40

"%.2f"% works on variables that are floats, not variables that contain floats. If you want to apply a function to the contents of an iterable, rather than the iterable itself, there are several options.

apply:
mean.apply(lambda x: "%.2f"%x)

List comprehension:
["%.2f"%x for x in mean] (this turns it into a list).

map:
df['mean']=mean.map(lambda x: '%.2f' % x) cf. Kaushal Sharma's answer

Panda's built-in rounding function:
mean=round(Xa.mean(axis=1),2) cf. LevB's answer.

BTW, there's no need to put the numbers into a numpy array before turning it into a dataframe.

If you replace the last bit of your code with the below, it works:

df['mean']=['%.2f'%row for row in mean]
Related