I want to compare column values from two different data frames, if both values match, insert a new Column in the data frame and add a value in the new column.
DF One:
col name col item
0 jo abc
1 bo efg
2 mo xyz
DF Two:
col name col item col code
0 jo abc , xyz 123
1 bo efg , xyz , zyx 456
2 mo abc, xyz 789
I'm trying to compare the col_name
and col_item
values in DF One to the values in DF Two. If the name
and item
from DF One match values from DF Two, pull the corresponding col code
value from DF Two into DF One. Each code number is set to a name and item. The results should look like this
DF One: End Result
col_name col_item new_col
0 jo abc 123
1 bo efg 789
2 mo xyz 456
Here is the code I've been trying. My logic is if name and item from DF Two match name and item from DF One, pull col code
value from DF Two into DF One
if df_two[' col name '] == df_one['col name '] & df_two [' col item '] == df_one[' col item ']:
df_one['new col'] = df_two['col code']
df_one.head(5).to_dict
{'Date': {0: '8/24/2021',
1: '8/17/2021',
2: '8/19/2021',
3: '8/19/2021',
4: '8/19/2021'},
'ID Number': {0: 123213,
1: 4564564',
2: '789789',
3: '735764',
4: '1010101'},
'col name': {0: 'mo',
1: 'bo',
2: 'jo,LLP',
3: 'do, LLP',
4: 'to, LLP'},
'Amount': {0: 900.0, 1: 105.0, 2: 1.02, 3: 132.0, 4: 8.0},
'Tax': {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0},
'col item': {0: ' abc - bc - zxy ',
1: ' cba - abc – zx ',
2: ' hij ',
3: ' lmn - op – xyz',
4: ' lmn - ac – mno'},
'BBNumber': {0: '30', 1: '30', 2: '30', 3: '30', 4: '30'}}
df_two.head(5).to_dict
{'Unnamed: 0': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4},
'col name': {0: 'mo',
1: 'bo',
2: 'jo,LLP',
3: 'do, LLP',
4: 'to, LLP'},
'col code': {0: 123, 1: 456, 2: 789, 3: 987, 4: 654},
'col item': {0: ' abc - bc - zxy, lmn - ac – mno, cba’,
1: cba - abc – zx, lmn - op - xyz',
2: 'hij , qrx',
3: ' lmn - op – xyz, abc’,
4: 'lmn - ac – mno’}}