Reputation: 475
column1 column2
0 name1 [(0, 0.12561743), (1, 0.12500079), (2, 0.1250000)]
1 name2 [(0, 0.1251732), (1, 0.12597172), (2, 0.623854998)]
How can I round off the values in column2 in 3 decimal places like this:
column1 column2
0 name1 [(0, 0.125), (1, 0.125), (2, 0.125)]
1 name2 [(0, 0.125), (1, 0.125), (2, 0.623)]
The following is not working as the values are in list:
df.column2 = df.column2.apply(lambda x: round(x, 2))
Upvotes: 0
Views: 438
Reputation: 31166
A list comprehension in apply()
works
import ast
df = pd.read_csv(io.StringIO(""" column1 column2
0 name1 [(0, 0.12561743), (1, 0.12500079), (2, 0.1250000)]
1 name2 [(0, 0.1251732), (1, 0.12597172), (2, 0.623854998)]"""), sep="\s\s+", engine="python")
df.column2 = df.column2.apply(ast.literal_eval)
df.column2 = df.column2.apply(lambda x: [(t[0], round(t[1],3)) for t in x])
column1 | column2 | |
---|---|---|
0 | name1 | [(0, 0.126), (1, 0.125), (2, 0.125)] |
1 | name2 | [(0, 0.125), (1, 0.126), (2, 0.624)] |
Upvotes: 1
Reputation: 150745
You need to loop twice:
# don't use .column2 to assign
df['column2'] = df.column2.apply(lambda x: [tuple(round(z, 3) for z in y) for y in x])
Output:
column1 column2
0 name1 [(0, 0.126), (1, 0.125), (2, 0.125)]
1 name2 [(0, 0.125), (1, 0.126), (2, 0.624)]
Upvotes: 2