How to map values using 3 columns?



Using pivot table, I am only able to find out Male who were married and irrespective of whether loan approved or not.
I want to find out Male who were married and were given Loan Status as ‘Yes’.

Snippet in Python -


I want to find using this code but 3 columns instead of 2.


Hey , to find “Male who were married and were given Loan Status as ‘Yes’” you can write all the three condition in your df.loc[…] . The following worked for me:

df.loc[(df["Gender"] == "Male") & (df["Married"] == "Yes") & (df["Loan_Status"] == "Y") ]


Thans for your answer. But it works like a Filter in Excel. Even i end up using with a count attribute still it shows all the columns count.
I want it to displayed something like this but with different columns :


0.0 0.078652
1.0 0.795789

How to use using pivot_table?


Hey @ASHISH_17,
You may try the following, which will get you the mean of Loan Status for all possible combinations of the 3 columns :

pivot = df.pivot_table(index=[‘Gender’,‘Married’,‘Credit_History’],values=‘Loan_Status’,aggfunc=lambda{‘Y’:1,‘N’:0}).mean())

Hope this helps :slight_smile:


Hello,I am trying to use the above code you just mentioned but I am getting an error.
raise KeyError(i)


Even I’m facing the same error!!


Just check that your dataframe df contains the column ‘Loan_Status’.


yeah, you are right. Loan_status column is missing in my data set. Thanks @shubham.jain


Hey there!
I too used pivot tables for mapping 3 columns like as mentioned above but I m unable to get a stacked bar of for ex. the probability of getting a loan by a mix of (Gender and Credit History). Can anyone please tell me how to do it?


Hi @ashita_smriti.1997,

The above code works fine for me. Here it is:



HI @ashita_smriti.1997 to plot the same graph following worked for me (After creating pivot_table the way @AishwaryaSingh mentioned):

temp4 = df.pivot_table(values='Loan_Status',index=['Credit_History','Gender'],aggfunc=lambda x:{'Y':1,'N':0}).mean())
temp4 = pd.crosstab(index=[df['Credit_History'], df['Gender']], columns=(df['Loan_Status']))
temp4.plot(kind = 'bar', stacked = True, color=['red','blue'])