根据另一列的值在 pandas 中创建新列 [英] Create new column in pandas based on value of another column

查看:76
本文介绍了根据另一列的值在 pandas 中创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些有关各个人的性别的数据集.说,数据集看起来像这样:

I have some dataset about genders of various individuals. Say, the dataset looks like this:

Male
Female
Male and Female
Male
Male
Female
Trans
Unknown
Male and Female

一些人将自己标识为男性,一些人将自己标识为男性和女性.

Some identify themselves as Male, some female and some identify themselves as both male and female.

现在,我想做的是在Pandas中创建一个新列来映射

Now, what I want to do is create a new column in Pandas which maps

Males to 1, 
Females to 2,
Others to 3

我写了一些代码

def gender(x):
    if x.str.contains("Male")
        return 1
    elif x.str.contains("Female")
        return 2
    elif return 3

df["Gender Values"] = df["Gender"].apply(gender)

但是我收到错误消息,该函数不包含任何属性.我尝试删除了str:

But I was getting errors that function doesn't contain any attribute contains. I tried removing str:

x.contains("Male")

我遇到了同样的错误

有更好的方法吗?

推荐答案

您可以使用:

def gender(x):
    if "Female" in x and "Male" in x:
        return 3
    elif "Male" in x:
        return 1
    elif "Female" in x:
        return 2
    else: return 4

df["Gender Values"] = df["Gender"].apply(gender)

print (df)
            Gender  Gender Values
0             Male              1
1           Female              2
2  Male and Female              3
3             Male              1
4             Male              1
5           Female              2
6            Trans              4
7          Unknown              4
8  Male and Female              3

这篇关于根据另一列的值在 pandas 中创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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