Reputation: 47
I'm attempting to append a column to my data frame, but am not entirely how to do so because the row indices on the dataframe I'm appending to are out of order.
My dataframe looks something like this (though not so simple):
|---------|
| Country |
----|---------|
1 | A |
----|---------|
2 | A |
----|---------|
5 | B |
----|---------|
6 | B |
----|---------|
3 | C |
----|---------|
4 | C |
----|---------|
The column I'm trying to append looks more like this:
|---------|
| Business|
----|---------|
1 | 1 |
----|---------|
2 | 2 |
----|---------|
3 | 1 |
----|---------|
4 | 2 |
----|---------|
5 | 1 |
----|---------|
6 | 2 |
----|---------|
And I'm trying get a result looking like this:
|---------|----------|
| Country | Business |
----|---------|----------|
1 | A | 1 |
----|---------|----------|
2 | A | 2 |
----|---------|----------|
5 | B | 1 |
----|---------|----------|
6 | B | 2 |
----|---------|----------|
3 | C | 1 |
----|---------|----------|
4 | C | 2 |
----|---------|----------|
though if the indices were in their proper order after the appending, that's great too.
How should I approach this using the pandas library? I've tried pandas.merge() but since I don't have an actual column with row indices, I'm not sure what to tell it to match on.
Sorry if this question has been asked before! I appreciate any help.
Upvotes: 1
Views: 3694
Reputation: 2810
you can try this:
df_merged = df1.merge(df2, how='outer', left_index=True, right_index=True)
Upvotes: 3