Skip to content Skip to sidebar Skip to footer

Merging Two Dataframe On Column And Index

Hi so I have two dataframes, first one is a dataframe which was created by grouping by another df by id (which is index now) and then sorting by 'due' column. df1: paid

Solution 1:

You can use rename for map by dict:

df1['name'] = df1.rename(index=df2.set_index('id')['name']).index
print (df1)
     paid  due   name
id                   
3    13.0  5.0   'EF'
2   437.0  5.0   'CD'
5    90.0  5.0  'NOP'
1    60.0  5.0   'AB'
4   675.0  5.0  'HAH'

Solution 2:

You might find that pd.concat is a better option here because it can accept a mix of dataframe and series: http://pandas.pydata.org/pandas-docs/stable/merging.html#concatenating-with-mixed-ndims.


Solution 3:

Okay so I figured out that I can't really get one column of dataframe in that way but I can remake df2 so that it contains only one needed column:

df2=df2[['id', 'name']]
pd.merge(df1, df2, left_index=True, right_on='id')

And there is no error anymore.


Post a Comment for "Merging Two Dataframe On Column And Index"