Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas: Update multiple rows using list

I am trying to update pandas dataframe using list.

Dataframe with columns A, B, C

A B C
------
1 a F
2 b F
3 c F
4 d F
5 e F

I have 2 lists, one contains list of elements whose value needs to update from column B and second contains actual value to replace in column C.

Elements to update from column B names=[‘a’, ‘d’, ‘e’]
Values to replace in column C values=[‘T’, ‘T’, ‘G’]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output after update

A B C
------
1 a T
2 b F
3 c F
4 d T
5 e G

How to update the dataframe?

>Solution :

You can use boolean indexing combined with map:

names = ['a', 'd', 'e']
values = ['T', 'T', 'G']

m = df['B'].isin(names)
df.loc[m, 'C'] = df.loc[m, 'B'].map(dict(zip(names, values)))

Less efficient alternatives:

df['C'] = df['B'].map(dict(zip(names, values))).fillna(df['C'])

df['C'] = df['C'].mask(df['B'].isin(names), df['B'].map(dict(zip(names, values))))

Output:

   A  B  C
0  1  a  T
1  2  b  F
2  3  c  F
3  4  d  T
4  5  e  G
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading