Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update/create column in pandas based on values in a list

Tags:

python

pandas

So, here is my dataframe

import pandas as pd
cols = ['Name','Country','Income']
vals = [['Steve','USA',40000],['Matt','UK',40000],['John','USA',40000],['Martin','France',40000],]
x = pd.DataFrame(vals,columns=cols)

I have another list:

europe = ['UK','France']

I want to create a new column 'Continent' if x.Country is in europe

like image 642
Pankaj Singh Avatar asked Dec 03 '22 21:12

Pankaj Singh


1 Answers

You need numpy.where with condition with isin:

x['Continent'] = np.where(x['Country'].isin(europe), 'Europe', 'Not Europe')
print (x)
     Name Country  Income   Continent
0   Steve     USA   40000  Not Europe
1    Matt      UK   40000      Europe
2    John     USA   40000  Not Europe
3  Martin  France   40000      Europe
like image 136
jezrael Avatar answered Dec 06 '22 09:12

jezrael