I have a dataframe of floats and I need make a function that will take a column and round all the values to N number of significant figures
So the column might look something like:
123.949
23.87
1.9865
0.0129500
and if I wanted to round to 3 significant figures I would pass the column and 3 to the function to get this
124.0
23.9
1.99
0.013
How can I do this efficiently without looping through the column?
I have an equation that will calculate the significant figures for a number
round(x, N-int(floor(log10(abs(x))))
but it doesn't work on a series or dataframe
You can use, pandas.Series.apply
which implements a function element wise across an axis (column or row):
df.col.apply(lambda x: round(x, N - int(floor(log10(abs(x))))))
Note that you can't really use pandas.DataFrame.apply
here since the round function should be element wise, not on the entire axis.
The difference would be that your function input is float
instead of getting an array
.
Another option would be applymap
which implements a function element-wise on the entire pandas.DataFrame
.
df.applymap(lambda x: round(x, N - int(floor(log10(abs(x))))))