Skip to main content
 首页 » 编程设计

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

2025年05月04日15sharpest

所以,这是我的数据框

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”

请您参考如下方法:

你需要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