1

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.

1

1 Answer 1

3

you can try this:

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

Sign up to request clarification or add additional context in comments.

1 Comment

Wouldn't it be simpler to use pandas.DataFrame.join()?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.