TheRealFakeNews
TheRealFakeNews

Reputation: 8143

Pandas: how to increment a column's cell value based on a list of ids

I have a list of ids that correspond to the row of a data frame. From that list of ids, I want to increment a value of another column that intersects with that id's row.

What I was thinking was something like this:

ids = [1,2,3,4]

for id in ids:
    my_df.loc[my_df['id']] == id]['other_column'] += 1

But this doesn't work. How can I mutate the original df, my_df?

Upvotes: 16

Views: 53707

Answers (2)

NickBraunagel
NickBraunagel

Reputation: 1599

the ids are unique, correct? If so, you can directly place the id into the df:

ids = [1,2,3,4]

for id in ids:
    df.loc[id,'column_name'] = id+1

Upvotes: 3

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210832

try this:

my_df.loc[my_df['id'].isin(ids), 'other_column'] += 1

Demo:

In [233]: ids=[0,2]

In [234]: df = pd.DataFrame(np.random.randint(0,3, (5, 3)), columns=list('abc'))

In [235]: df
Out[235]:
   a  b  c
0  2  2  1
1  1  0  2
2  2  2  0
3  0  2  1
4  0  1  2

In [236]: df.loc[df.a.isin(ids), 'c'] += 100

In [237]: df
Out[237]:
   a  b    c
0  2  2  101
1  1  0    2
2  2  2  100
3  0  2  101
4  0  1  102

Upvotes: 21

Related Questions