Skip to main content
 首页 » 编程设计

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

2025年05月04日14www_RR

需要有关 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 是乘客 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 

上述代码的问题在于它在 df 中创建了一个 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。

那么为什么 df 变量会出错呢?我什至尝试先定义一个函数然后调用它。给出了与第一个相同的答案。

那么,我们如何在 pandas 中做到这一点?

其次,我想如果我们可以只使用一些多个 if-else 语句,也可以做到同样的事情。我知道 np.where 但它不允许添加“和”条件。所以这就是我正在尝试的:

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

上面给出了 'and' 关键字错误的位置。

那么有人可以帮忙吗?非常感谢使用 np.where(简单的 if-else 之类)和使用某些函数(applymap 等)或修改我之前写的内容的多种方法的解决方案。

另外,我们如何使用 df 的一些 applymap 或 apply/map 方法来做同样的事情?。

请您参考如下方法:

无需使用 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 是最后一个赋值,因此整个列最终都被零填充。

对于第二种方法,请注意您需要使用 & 而不是 and 对两个 NumPy 数组执行elementwise 逻辑与运算或 Pandas NDFrame。因此,您可以使用

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