python - Pandas: how to increment a column's cell value based on a list of ids -
i have list of ids correspond row of data frame. list of ids, want increment value of column intersects id's row.
what thinking this:
ids = [1,2,3,4] id in ids: my_df.loc[my_df['id']] == id]['other_column'] += 1
but doesn't work. how can mutate original df, my_df
?
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]: 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]: b c 0 2 2 101 1 1 0 2 2 2 2 100 3 0 2 101 4 0 1 102
Comments
Post a Comment