0

I am wanting to divide column a by 10 when groupby id = 2 and update the original df. Not too sure how to do this one!

df

            date  id   a    b    c   d
    0   1/1/2000   1  10   20  10.0  11
    1   1/1/2000   2  100  21   1.0  11
    2   1/1/2000   3  15   20  14.0  11
    3   1/1/2000   4  10   24  13.0  11
    4   1/2/2000   1  10   25  10.0  11
    5   1/2/2000   2  100  20  13.0  15
    6   1/2/2000   3  10   26  22.0  11
    7   1/2/2000   4  10   20  16.0  13
    8   1/3/2000   1  10   20  10.0  11
    9   1/3/2000   2  100  20  13.0  11
    10  1/3/2000   3  10   20  18.0  11
    11  1/3/2000   4  10   20  10.0  11

desired dataframe

        date  id   a    b    c   d
0   1/1/2000   1  10   20  10.0  11
1   1/1/2000   2  10   21   1.0  11
2   1/1/2000   3  15   20  14.0  11
3   1/1/2000   4  10   24  13.0  11
4   1/2/2000   1  10   25  10.0  11
5   1/2/2000   2  10   20  13.0  15
6   1/2/2000   3  10   26  22.0  11
7   1/2/2000   4  10   20  16.0  13
8   1/3/2000   1  10   20  10.0  11
9   1/3/2000   2  10   20  13.0  11
10  1/3/2000   3  10   20  18.0  11
11  1/3/2000   4  10   20  10.0  11
oceanbeach96
  • 604
  • 9
  • 19

2 Answers2

1

Use boolean indexing along the first axis and update column a in-place:

df.loc[df['id'].eq(2), 'a'] /= 10
yatu
  • 86,083
  • 12
  • 84
  • 139
0

Using a lambda

df['a'] = df.apply(lambda x: x['a']/100 if x['id']==2 else x['a'],axis=1)
df

+----------+------+-----+-----+-----+-----+
|          |   id |   a |   b |   c |   d |
+==========+======+=====+=====+=====+=====+
| 1/1/2000 |    1 |  10 |  20 |  10 |  11 |
| 1/1/2000 |    2 |   1 |  21 |   1 |  11 |
| 1/1/2000 |    3 |  15 |  20 |  14 |  11 |
| 1/1/2000 |    4 |  10 |  24 |  13 |  11 |
| 1/2/2000 |    1 |  10 |  25 |  10 |  11 |
| 1/2/2000 |    2 |   1 |  20 |  13 |  15 |
| 1/2/2000 |    3 |  10 |  26 |  22 |  11 |
| 1/2/2000 |    4 |  10 |  20 |  16 |  13 |
| 1/3/2000 |    1 |  10 |  20 |  10 |  11 |
| 1/3/2000 |    2 |   1 |  20 |  13 |  11 |
| 1/3/2000 |    3 |  10 |  20 |  18 |  11 |
| 1/3/2000 |    4 |  10 |  20 |  10 |  11 |
+----------+------+-----+-----+-----+-----+
Equinox
  • 6,483
  • 3
  • 23
  • 32
  • 1
    check [this](https://stackoverflow.com/questions/54432583/when-should-i-ever-want-to-use-pandas-apply-in-my-code) - your solution is not recommended because performance – jezrael Oct 14 '20 at 12:46