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

时间:2014-03-19 11:25:51

标签: python if-statement pandas where

需要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

根据上述逻辑,这给出了一个dict预测,其中键为ID,值为1或0。

那么为什么df变量工作错误?我甚至尝试先定义一个函数然后调用它。和第一个一样。

那么,我们怎么能在熊猫中做到这一点?

其次,如果我们可以使用一些多个if-else语句,我想也可以这样做。我知道np.where但它不允许添加&#39;和&#39;条件。所以这就是我的尝试:

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

上面给出的错误是&#39;和&#39;关键字在哪里。

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

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

1 个答案:

答案 0 :(得分:7)

您可以使用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阵列或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