Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine Dataframes With Different Indexes in Pandas [duplicate]

Tags:

python

pandas

I have two dataframes:

df1 : here index is ip

            accountname      name
ip
192.168.1.1        aaaa  john doe
192.168.1.2        bbbb  jane doe

df2 : index is accountname

             gsm
accountname
aaaa         850
bbbb         860
cccc         870

I have to combine two dataframe and add gsm column to df1.

            ip accountname      name  gsm
0  192.168.1.1        aaaa  john doe  850
1  192.168.1.2        bbbb  jane doe  860

These dataframes has different indexes and I couldnt reach right data. any advice would be appreciated.

like image 551
jojo Avatar asked Oct 15 '17 12:10

jojo


People also ask

How avoid duplicates in Pandas merge?

merge() function to join the two data frames by inner join. Now, add a suffix called 'remove' for newly joined columns that have the same name in both data frames. Use the drop() function to remove the columns with the suffix 'remove'. This will ensure that identical columns don't exist in the new dataframe.

How do I merge two DataFrames in Pandas without duplicates?

To concatenate DataFrames, use the concat() method, but to ignore duplicates, use the drop_duplicates() method.

Can you merge two DataFrames of different lengths Pandas?

It can be done using the merge() method. Below are some examples that depict how to merge data frames of different lengths using the above method: Example 1: Below is a program to merge two student data frames of different lengths.


1 Answers

You could use merge with index as well.

In [2313]: df1.merge(df2, left_on='accountname', right_index=True).reset_index()
Out[2313]:
            ip accountname      name  gsm
0  192.168.1.1        aaaa  john doe  850
1  192.168.1.2        bbbb  jane doe  860
like image 90
Zero Avatar answered Sep 30 '22 08:09

Zero