I'm trying to create a new category column from two different Pandas dataframes that contain the same columns using Pandas.
The new column looks at both Df1 and Df2's 'Loan Code/Number' column, determines if they're the same then determines if the 'Del_Cat' category changed from Df1 to Df2, and if it changed categories, it will return a new result.
DF1:
| Loan Code/Number | Days Delinquent | Del_Cat |
|---|---|---|
| 1147623994 | -25 | Current |
| 1501719058 | -5 | Current |
| 1501719696 | 77 | 61-90 |
| 1502624989 | 87 | 61-90 |
| 1502625152 | 16 | Current |
DF2:
| Loan Code/Number | Days Delinquent | Del_Cat |
|---|---|---|
| 1147623994 | -22 | Current |
| 1801719152 | 37 | 31-60 |
| 1501719696 | 84 | 61-90 |
| 1602624414 | -6 | Current |
| 1502625152 | 55 | 31-60 |
I've tried creating a function that loops over the values in the tables and determines if the loan number is the same, and if it is then to check the values in the 'Del_Cat' column, bringing back a new value that states if the value has changed:
def del_cat_migration(df1, df2):
if [df1['Loan Code/Number'] == df2['Loan Code/Number']]:
if (df1['Del_Cat']) == 'Current' & (df2['Del_Cat']) == 'Current':
return 'Same - Current'
elif (df1['Del_Cat']) == 'Current' & (df2['Del_Cat']) == '31-60':
return 'Current to 31-60'
elif (df1['Del_Cat']) == '31-60' & (df2['Del_Cat']) == '31-60':
return 'Same - 31-60'
elif (df1['Del_Cat']) == '31-60' & (df2['Del_Cat']) == '61-90':
return '31-60 to 61-90'
elif (df1['Del_Cat']) == '61-90' & (df2['Del_Cat']) == '61-90':
return 'Same - 61-90'
elif (df1['Del_Cat']) == '61-90' & (df2['Del_Cat']) == 'Current':
return '61-90 to Current'
else:
return 'Other'
I then try to apply this new data to a new column in df2:
df2['Del_Migration_Cat'] = df2.apply(del_cat_migration(df1, df2), axis = 1)
I then get the following error:
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
These are the dataframes:
import pandas as pd
df1 = pd.DataFrame({"Loan Code/Number":[1147623994, 1501719058, 1501719696, 1502624989, 1502625152],
"Days Delinquent":[-25,-5,77,87,16],
"Del_Cat":["Current","Current","61-90","61-90","Current"]})
df2 = pd.DataFrame({"Loan Code/Number":[1147623994, 1801719152, 1501719696, 1602624414, 1502625152],
"Days Delinquent":[-22,37,84,-6,55],
"Del_Cat":["Current","31-60","61-90","Current","31-60"]})