如何基于列表中的值更新/创建 pandas 中的列 [英] How to update/create column in pandas based on values in a list

查看:40
本文介绍了如何基于列表中的值更新/创建 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'

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

推荐答案

或者您可以直接使用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

这篇关于如何基于列表中的值更新/创建 pandas 中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆