Home > Back-end >  How to loop through a column and compare each value to a list
How to loop through a column and compare each value to a list

Time:06-22

I have a column in a dataset. I need to compare each value from that column to a list. After comparison, if it satisfies a condition, the value of another column should change. for example,

enter image description here

List- james, michael, clara

According to the code, if a name in col A is in the list, col B should be 1, else 0. How to solve this in python

CodePudding user response:

Change B column where value A is in List

Using the loc operator you can easily select the rows where the item in the A column is in your List, and change the B column of these rows.

df.loc[(df["A"].isin(List)), "B"] = 1

Use np.fillna to fill empty cells with zeros.

df.fillna(0, inplace=True) 

Full Code

names = ['james', 'randy', 'mona', 'lisa', 'paul', 'clara']
List = ["james", "michael", "clara"]
df = pd.DataFrame(data=names, columns=['A'])
df["B"] = np.nan

df.loc[(df["A"].isin(List)), "B"] = 1
df.fillna(0, inplace=True) 

CodePudding user response:

This would be a good time to use np.where()

import pandas as pd
import numpy as np

name_list = ['James', 'Sally', 'Sarah', 'John']
df = pd.DataFrame({
    'Names' : ['James', 'Roberts', 'Stephen', 'Hannah', 'John', 'Sally']
})

df['ColumnB'] = np.where(df['Names'].isin(name_list), 1, 0)
df
  • Related