Home > Back-end >  Select Multiple Conditions - 2 DataFrames - Create New Column
Select Multiple Conditions - 2 DataFrames - Create New Column

Time:11-17

I have 2 DataFrames:

DF1 - Master List

ID     Item
100    Wood
101    Steel
102    Brick
103    Soil

DF2

ID    
100    
103   

I want my final DataFrame to look like this:

ID     Item / ID
100    100 - Wood
103    103 - Soil

The issue I'm having is DF2 doesn't have the Item Column.

I could manually do it by np.select(conditions, choices, default='N/A') but the full dataset is huge and would take a lot of time.

I also tried an np.select from the 2 different datasets, citing the columns but got a Can only compare identically-labeled DataFrame objects. error.

Is there a way to pull the relevant information from Item so I can join the strings values from ID to create Item / ID

Thanks in advance

CodePudding user response:

dff = pd.merge(df1, df2, how = 'right', on = 'ID')
dff['Item / ID'] = dff['ID'].astype(str)   ' - '   dff['Item']
dff.drop('Item', axis=1, inplace=True)
print(dff)

output:

    ID   Item / ID
0  100  100 - Wood
1  103  103 - Soil
  • Related