I am trying to cut a column within a Pandas data frame column to 3 decimal places. I do not want to round the data, I just want to cut it so it will match other data. This is what I have tried; however, I get a TypeError: must be a real number, not list.
import pandas as pd
data = {'values': [5.52132, 6.572935, 7.21, 8.755, 9.9989]}
df = pd.DataFrame(data, columns = ['values'])
df['values'] = df['values'].astype(float).apply('%.3f'%['values'])
print(df))
CodePudding user response:
You can use the following answer: https://stackoverflow.com/a/29257837/3944480
i.e.:
import pandas as pd
import math
to_places = 3 # yours number of places 3
def truncate(f, n):
return math.floor(f * 10 ** n) / 10 ** n
data = {'values': [5.52132, 6.572935, 7.21, 8.755, 9.9989]}
df = pd.DataFrame(data, columns = ['values'])
print( df['values'].astype(float).apply(lambda number: truncate(number, to_places)) )
yielding:
0 5.521
1 6.572
2 7.210
3 8.755
4 9.998