0

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.

datanovice
  • 27
  • 4
  • 1
    Does this answer your question? [Merge two dataframes by index](https://stackoverflow.com/questions/40468069/merge-two-dataframes-by-index) – Mykola Zotko Jan 26 '20 at 17:41

1 Answers1

2

you can try this:

df_merged = df1.merge(df2, how='outer', left_index=True, right_index=True)

M_S_N
  • 2,271
  • 1
  • 12
  • 27
  • 1
    Wouldn't it be simpler to use [`pandas.DataFrame.join()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html#pandas-dataframe-join)? – AMC Jan 26 '20 at 19:07