1

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?

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

13 Comments

Excellent. It worked. Could you please, explain the significance or meaning of drop=True, axis=1 in concat code? Also, could you explain the significance or meaning of left-Index=True,right_index=True in Merge code?
OK, the best for drop=True is try remove it like c = pd.concat([a.iloc[2:4], b.iloc[2:4]], axis=1), then get not 0,1 index but 2,3
Ok. What about a.iloc'? I heard about a.loc? I mean, loc` and iloc are different?
axis=1 in concat mean you want join by columns, check docs The axis to concatenate along and similar for merge it join by both indexes.
@Msquare - I think better is is explained here
|

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.