使用多个If-else创建Pandas变量

1 投票
1 回答
13522 浏览
提问于 2025-04-17 22:57

我需要帮助,想在Pandas中使用多个IF-ELSE语句。我有一个测试数据集(泰坦尼克号),如下所示:

ID  Survived    Pclass  Name    Sex Age
1   0   3   Braund  male    22
2   1   1   Cumings, Mrs.   female  38
3   1   3   Heikkinen, Miss. Laina  female  26
4   1   1   Futrelle, Mrs.  female  35
5   0   3   Allen, Mr.  male    35
6   0   3   Moran, Mr.  male    
7   0   1   McCarthy, Mr.   male    54
8   0   3   Palsson, Master male    2

这里的Id是乘客的编号。我想在这个数据框中创建一个新的标记变量,规则如下:

if Sex=="female" or (Pclass==1 and Age <18) then 1 else 0. 

为了实现这个目标,我尝试了几种方法。首先,我是这样做的:

df=pd.read_csv(data.csv)
for passenger_index,passenger in df.iterrows():
    if passenger['Sex']=="female" or (passenger['Pclass']==1 and passenger['Age']<18):
       df['Prediction']=1
    else:
       df['Prediction']=0

上面的代码问题在于,它在数据框中创建了一个名为Prediction的变量,但所有的值都是0。

不过,如果我用同样的代码,但把结果输出到一个字典中,它就能给出正确的答案,如下所示:

prediction={}
df=pd.read_csv(data.csv)
for passenger_index,passenger in df.iterrows():
    if passenger['Sex']=="female" or (passenger['Pclass']==1 and passenger['Age']<18):
       prediction[passenger['ID']=1
    else:
       prediction[passenger['ID']=0

这会生成一个字典,键是ID,值是根据上述逻辑为1或0。

那么,为什么数据框的变量会出错呢?我甚至尝试先定义一个函数,然后再调用它,结果和第一次一样。

那么,我们该如何在Pandas中做到这一点呢?

其次,我想如果能使用一些多个if-else语句,应该也能实现。我知道np.where,但它不允许添加'and'条件。所以我尝试了这个:

df['Prediction']=np.where(df['Sex']=="female",1,np.where((df['Pclass']==1 and df['Age']<18),1,0)

上面的代码在where中对'and'关键字报错。

所以有人能帮忙吗?如果能提供使用np.where(类似简单的if-else)和一些函数(如applymap等)或对我之前写的内容进行修改的多种解决方案,我将非常感激。

另外,如何使用applymap或apply/map方法来实现相同的功能呢?

1 个回答

8

与其使用 df.iterrows 一行一行地遍历数据(这样比较慢),不如一次性把想要的值赋给 Prediction 这一列。

In [27]: df['Prediction'] = ((df['Sex']=='female') | ((df['Pclass']==1) & (df['Age']<18))).astype('int')

In [29]: df['Prediction']
Out[29]: 
0    0
1    1
2    1
3    1
4    0
5    0
6    0
7    0
Name: Prediction, dtype: int32

在你第一种方法中,要记住 df['Prediction'] 代表的是整个 df 的一列,所以 df['Prediction']=1 这行代码会把1赋给这一列的每一行。由于最后一次赋值是 df['Prediction']=0,所以整列最后都变成了0。

在你第二种方法中,要注意使用 & 而不是 and 来对两个 NumPy 数组或 Pandas NDFrames 进行逐个元素的逻辑与操作。因此,你可以使用

In [32]: np.where(df['Sex']=='female', 1, np.where((df['Pclass']==1)&(df['Age']<18), 1, 0))
Out[32]: array([0, 1, 1, 1, 0, 0, 0, 0])

不过我觉得直接用 | 来做逻辑或,用 & 来做逻辑与会简单很多:

In [34]: ((df['Sex']=='female') | ((df['Pclass']==1) & (df['Age']<18)))
Out[34]: 
0    False
1     True
2     True
3     True
4    False
5    False
6    False
7    False
dtype: bool

撰写回答