如何根据列表中的值更新/创建pandas中的列

时间:2017-08-28 14:12:19

标签: python pandas

所以,这是我的数据框

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)

我有另一个清单:

europe = ['UK','France']

如果x.Country位于欧洲

,我想创建一个新列'Continent'

2 个答案:

答案 0 :(得分:6)

您需要numpy.where条件为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

答案 1 :(得分:5)

或者您可以直接使用isin

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