Pandas variable rounding of column

>>> print(df)
  item  value1
0    a    1.121
1    a    1.510
2    a    0.110
3    b    3.322
4    b    4.811
5    c    5.841

This is my dummy pandas df.

Below is how I truncate/round my column value1.

decimals = 2    
df['value1'] = df['value1'].apply(lambda x: round(x, decimals))
>>> print(df)
  item  value1
0    a    1.12
1    a    1.51
2    a    0.11
3    b    3.32
4    b    4.81
5    c    5.84

This truncate all the two column to two decimal point after decimal. Is it possible to have variable rounding w dictionary. So in below we see 'a' = two places post decimal, 'b': 3 post decimal....default(value not convered....default to 2). My expected df below. Not sure if this is possible. (More of thought experimentation)

dec_dict = {'a' : 2, 'b': 3, 'l':3, 'default': 2}

>>> print(df)
  item  value1
0    a    1.12
1    a    1.51
2    a    0.11
3    b    3.322
4    b    4.811
5    c    5.84

Solution 1:

Given the fact that trailing zeros are not significant, the best approach should be:

dec_dict = {'a' : 2, 'b': 3, 'l':3, 'default': 2}

df['value1'] = (df.groupby('item')['value1']
                  .apply(lambda g: g.round(dec_dict.get(g.name, dec_dict['default']))
                )

output:

  item  value1
0    a   1.120
1    a   1.510
2    a   0.110
3    b   3.322
4    b   4.811
5    c   5.840