Merge or concat two df by index
Question:
I have the following issue: I want to concat or merge two dataframes with different length and partly different indexes:
data1:
index
data1
1
16
2
37
3
18
7
49
data2:
index
data2
2
74
3
86
4
12
6
97
12
35
They should be merged in the way, that the output looks like:
index
data1
data2
1
16
NaN
2
37
74
3
18
86
4
NaN
12
6
NaN
97
7
49
NaN
12
NaN
35
I hope you can help me out.
Thanks in advance
Answers:
You can use join
:
out = df1.join(df2, how='outer')
print(out)
# Output
data1 data2
index
1 16.0 NaN
2 37.0 74.0
3 18.0 86.0
4 NaN 12.0
6 NaN 97.0
7 49.0 NaN
12 NaN 35.0
Or you can use merge
:
out = df1.merge(df2, left_index=True, right_index=True, how='outer')
Or you can use concat
:
out = pd.concat([df1, df2], axis=1).sort_index()
I have the following issue: I want to concat or merge two dataframes with different length and partly different indexes:
data1:
index | data1 |
---|---|
1 | 16 |
2 | 37 |
3 | 18 |
7 | 49 |
data2:
index | data2 |
---|---|
2 | 74 |
3 | 86 |
4 | 12 |
6 | 97 |
12 | 35 |
They should be merged in the way, that the output looks like:
index | data1 | data2 |
---|---|---|
1 | 16 | NaN |
2 | 37 | 74 |
3 | 18 | 86 |
4 | NaN | 12 |
6 | NaN | 97 |
7 | 49 | NaN |
12 | NaN | 35 |
I hope you can help me out.
Thanks in advance
You can use join
:
out = df1.join(df2, how='outer')
print(out)
# Output
data1 data2
index
1 16.0 NaN
2 37.0 74.0
3 18.0 86.0
4 NaN 12.0
6 NaN 97.0
7 49.0 NaN
12 NaN 35.0
Or you can use merge
:
out = df1.merge(df2, left_index=True, right_index=True, how='outer')
Or you can use concat
:
out = pd.concat([df1, df2], axis=1).sort_index()