I have a pandas data frame which having three columns. Normally for the Loan type it has 5 values. Let's say Conso, Immo, Pro, Autre, Tous. For this data frame only contain loan type 'Immo'. (At the beginning we don't know what the Loan type is). How do I check what the loan type is among all this loan type?
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)
As a output I'm getting 0 for Answer Column. How do I get expected out put as I explained?
If want check if exist all values in L
in column LoanType
use:
L = ['Immo', 'Conso', 'Pro', 'Autres', 'Tous']
a = all([(df['LoanType'] == x).any() for x in L])
print (a)
False
Or:
s = set(['Immo', 'Conso', 'Pro', 'Autres', 'Tous'])
a = s.issubset(set(df['LoanType'].tolist()))
print (a)
False
EDIT:
If your solution return 0
there is no match.
I guess some traling whitespaces, so need remove them first by strip
:
df1['Answer'] = df1.LoanType.str.strip().map(check_type_pret)
Another solution with numpy.where
or where
and condition with isin
:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.