如何检查Pandas数据框中同一列中所有其他值的列值?

问题描述 投票:0回答:1

我有一个有三列的pandas数据框。通常对于贷款类型,它有5个值。让我们说Conso,Immo,Pro,Autre,Tous。对于此数据框,仅包含贷款类型“Immo”。 (一开始我们不知道贷款类型是什么)。如何检查所有贷款类型中的贷款类型?

CodeProduit  LoanType   Year
301          Immo       2003
301          Immo       2004
301          Immo       2005
301          Immo       2006
...          ...        ....
301          Immo       2017

def check_type_pret(p):
    if p == 'Immo':
         return p
    elif p == 'Conso':
        return p
    elif p == 'Pro':
        return p
    elif p == 'Autres':
        return p
    elif p == 'Tous':
        return p
    else:
        return 0



df1['Answer']=df1.LoanType.map(check_type_pret)

作为输出,我的答案栏为0。如我解释的那样如何得到预期的输出?

python pandas dataframe
1个回答
1
投票

如果要检查是否存在L列中LoanType中的所有值使用:

L = ['Immo', 'Conso', 'Pro', 'Autres', 'Tous']
a = all([(df['LoanType'] == x).any() for x in L])
print (a)
False

要么:

s = set(['Immo', 'Conso', 'Pro', 'Autres', 'Tous'])
a = s.issubset(set(df['LoanType'].tolist()))
print (a)
False

编辑:

如果您的解决方案返回0则无法匹配。

我猜一些尾随空格,所以需要首先通过strip删除它们:

df1['Answer'] = df1.LoanType.str.strip().map(check_type_pret)

numpy.wherewhereisin条件的另一个解决方案:

print (df1)
   CodeProduit LoanType  Year
0          301    Immo1  2003
1          301    Conso  2004
2          301      Pro  2005
3          301   Autres  2006
4          301     Tous  2017

df1.LoanType = df1.LoanType.str.strip()

L = ['Immo', 'Conso', 'Pro', 'Autres', 'Tous']
df1['Answer'] = np.where(df1.LoanType.isin(L), df1.LoanType, 0)
#another solution
#df1['Answer'] = df1.LoanType.where(df1.LoanType.isin(L),  0)
print (df1)
   CodeProduit LoanType  Year  Answer
0          301    Immo1  2003       0
1          301    Conso  2004   Conso
2          301      Pro  2005     Pro
3          301   Autres  2006  Autres
4          301     Tous  2017    Tous
© www.soinside.com 2019 - 2024. All rights reserved.