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

后端 未结 2 1996
遥遥无期
遥遥无期 2020-12-21 15:52

So, here is my dataframe

import pandas as pd
cols = [\'Name\',\'Country\',\'Income\']
vals = [[\'Steve\',\'USA\',40000],[\'Matt\',\'UK\',40000],[\'John\',\'U         


        
相关标签:
2条回答
  • 2020-12-21 16:41

    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
    
    0 讨论(0)
  • 2020-12-21 16:42

    Or you can using isin directly

    x['New Column']='Not Europe'
    x.loc[x.Country.isin(europe),'New Column']='Europe'
    
    Out[612]: 
         Name Country  Income  New Column
    0   Steve     USA   40000  Not Europe
    1    Matt      UK   40000      Europe
    2    John     USA   40000  Not Europe
    3  Martin  France   40000      Europe
    
    0 讨论(0)
提交回复
热议问题