如何在dataframe中根据某一列的数筛选出与另一数组存在的行

game2['color'].loc[game2['id'] in [red]]='red'
game2为dataframe,red为一个list
想实现id存在于red中对应的color改为‘red’

使用where函数选取,这样操作试试:

import pandas as pd

red=['112','113','115']
game2=pd.DataFrame({'id':['101','111','113','115'],'color':['black','yellow','green','blue']})
game2['color'].where(~game2['id'].isin(red), 'red',inplace=True)#id不在列表中保持原值,否则改为'red'
print(game2)

如有帮助,请点采纳。