lundi 19 juillet 2021

If and function in pandas

I'm new to python and I'm trying to find some thing like If and elif for my case. My code as below:

import pandas as pd
df = pd.DataFrame({'v_contract_number': ['VN120001438','VN120001439',
                                          'VN120001440','VN120001438',
                                          'VN120001439','VN120001440'],
                                            'Collateral': ['Real Estate','Real Estate','Gold','Gold','Deposit','Deposit'],
                                        'Purpose': [20,30,20,30,20,30]})

# df
    v_contract_number   Collateral  Purpose
0   VN120001438 Real Estate 20
1   VN120001439 Real Estate 30
2   VN120001440 Gold    20
3   VN120001438 Gold    30
4   VN120001439 Deposit 20

cols = ['Collateral', 'Purpose']
df['combined'] = df[cols].apply(lambda row: '_'.join(row.values.astype(str)), axis=1)
df['v_purpose'] = df['combined'].apply(lambda x:'Real Estate Loan' if x == "Real Estate_20" else 'Others')
df.head()

#df
v_contract_number   Collateral  Purpose combined    v_purpose
0   VN120001438 Real Estate 20  Real Estate_20  Real Estate Loan
1   VN120001439 Real Estate 30  Real Estate_30  Others
2   VN120001440 Gold    20  Gold_20 Others
3   VN120001438 Gold    30  Gold_30 Others
4   VN120001439 Deposit 20  Deposit_20  Others

But I want to add more conditions to combined column like:

if df['combined'] == "Real Estate_20":
   df['v_purpose'] == "Real Estate Loan"
elif df['combined'] == "Real Estate_30":
   df['v_purpose'] == "Home Mortgage Loan"
else
   df['v_purpose'] == "Others"

Thank for your help

Aucun commentaire:

Enregistrer un commentaire