Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas replace multiple values

Below is sample dataframe

>>> df = pd.DataFrame({'a': [1, 1, 1, 2, 2],  'b':[11, 22, 33, 44, 55]})
>>> df
      a   b
   0  1  11
   1  1  22
   2  1  33
   3  2  44
   4  3  55

Now I wanted to update/replace b values that are matched on a column from other dict based on index

ex:

match = {1:[111, 222], 2:[444, 555]}

output:

      a   b
   0  1  111
   1  1  222
   2  1  33  <-- ignores this bcz not enough values to replace in match dict for 1 
   3  2  444
   4  3  555

Thanks in advance

like image 939
sunny Avatar asked Jan 28 '23 11:01

sunny


1 Answers

Here's one way. The idea is to calculate a cumulative count by group and use this to filter rows. Use itertools.chain to create a single array of values. Finally, use pd.DataFrame.loc and Boolean indexing to set values.

from itertools import chain

count = df.groupby('a').cumcount() + 1

m1 = df['a'].isin(match)
m2 = count.le(df['a'].map(match).map(len))
values = list(chain.from_iterable(match.values()))

df.loc[m1 & m2, 'b'] = values

print(df)

   a    b
0  1  111
1  1  222
2  1   33
3  2  444
4  2  555
like image 55
jpp Avatar answered Jan 31 '23 09:01

jpp