I have 2 dataframes I want to merge together. In df1 it has an 'id' of A, B, C,... and in df2 it has an 'id' of A1, A2, A3, ..., B1, B2, B3... I want to merge them on condition of df1.id in df2.id
. I've looked at tutorials, and searched StackOverflow, but not seeing anything relevant.
The keys of df1 is a subset of the keys in df2. So a simple pd.merge(df1, df2, on='id', how...) results in a dataframe that's not correct.
SETUP:
dummy_data1 = {
'id': ['A', 'B', 'C', 'D', 'E'],
'Feature1': ['1', '2', '3', '4', '5'],
'Feature2': ['6', '7', '8', '9', '10']}
dummy_data2 = {
'id': ['A1', 'A2', 'A3', 'B1', 'B2'],
'Feature1': ['a', 'b', 'c', 'd', 'e'],
'Feature2': ['f', 'g', 'h', 'i', 'j']}
df1 = pd.DataFrame(dummy_data1, columns = dummy_data1.keys())
df2 = pd.DataFrame(dummy_data2, columns = dummy_data2.keys())
Desired output:
id Feature1_x Feature2_x Feature1_y Feature2_y
0 A1 1 6 a f
1 A2 1 6 b g
2 A3 1 6 c h
3 B1 2 7 d i
4 B2 2 7 e j
ATTEMPT 1:
newdf = pd.merge(df1['id'], df2['id'], on='id', how='inner')
RESULT 1:
Empty DataFrame
Columns: [id]
Index: []
ATTEMPT 2:
newdf = pd.merge(df1['id'], df2['id'], on='id', how='outer')
RESULT 2:
id
0 A
1 B
2 C
3 D
4 E
5 A1
6 A2
7 A3
8 B1
9 B2
ATTEMPT 3:
newdf = pd.merge(df1['id'], df2['id'].str[:1], on='id', how='inner')
RESULT 3:
id
0 A
1 A
2 A
3 B
4 B