2

I have 2 Dataframes as below:

Dataframe1:

   6     count
store_1   10
store_2   23
store_3   53

Dataframe2:

store_name  location
store_1     location_a
store_2     location_b

I am trying to join the above two Dataframes such that I get the below output:

   6     count  location
store_1   10    location_a
store_2   23    location_b
store_3   53

I am trying to merge Dataframe1 with Dataframe2 using index id of the column and not by the column name.

3
  • 6 is an index or a column? similarly store_name ? Commented Apr 13, 2019 at 12:51
  • @anky_91, the first row are the column names. I am trying to build this such that it tries to join the two dataframes using the first column in each of the dataframes. Hence I am trying to join them by first column of the Dataframe Commented Apr 13, 2019 at 12:53
  • 1
    how does this work? df1.set_index(6).combine_first(df.set_index('store_name')) Commented Apr 13, 2019 at 13:02

2 Answers 2

2

Left merge on indexes would work for you.

data = {'6': ['store1', 'store2', 'store3'], 'count': [10, 23, 53]}
df1 = pd.DataFrame(data).set_index('6')
df1

enter image description here

data = {'store_name': ['store1', 'store2'], 'location': ['location_a', 'location_b']}
df2 = pd.DataFrame(data).set_index('store_name')
df2

enter image description here

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

enter image description here

Hope this helps.

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

Comments

1
pd.concat([df1, df2], axis=1)

simply adds columns (axis=1) from df2 to 1st data frame

Comments

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.