Msquare
Msquare

Reputation: 373

Python Pandas Merge data from different Dataframes on specific index and create new one

My code is given below: I have two data frames a,b. I want to create a new data frame c by merging a specific index data of a, b frames.

import pandas as pd
a = [10,20,30,40,50,60]
b = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
a = pd.DataFrame(a,columns=['Voltage'])
b = pd.DataFrame(b,columns=['Current'])
c = pd.merge(a,b,left_index=True, right_index=True)
print(c)

The actual output is:

     Voltage  Current
0       10      0.1
1       20      0.2
2       30      0.3
3       40      0.4
4       50      0.5
5       60      0.6

I don't want all the rows. But, specific index rows something like:

c =      Voltage Current
     0     30      0.3
     1     40      0.4

How to modify c = pd.merge(a,b,left_index=True, right_index=True) code so that, I only want those specific third and fourth rows in c with new index order as given above?

Upvotes: 1

Views: 5229

Answers (1)

jezrael
jezrael

Reputation: 862581

Use iloc for select rows by positions and add reset_index with drop=True for default index in both DataFrames:

Solution1 with concat:

c = pd.concat([a.iloc[2:4].reset_index(drop=True),
               b.iloc[2:4].reset_index(drop=True)], axis=1)

Or use merge:

c = pd.merge(a.iloc[2:4].reset_index(drop=True),
             b.iloc[2:4].reset_index(drop=True), 
             left_index=True, 
             right_index=True)

print(c)
   Voltage  Current
0       30      0.3
1       40      0.4

Upvotes: 2

Related Questions