Batuhan Bardak Batuhan Bardak - 2 months ago 10
Python Question

Reduction the Pandas dataframe to other dataframe

I have two data frames and their shapes are (

707
,
140
) and (
34
,
98
).

I want to minimize the bigger data frame to the small one based on the same index name and column names.

So after the removing additional rows and columns from bigger data frame, in the final its shape should be (
34
,
98
) with the same index and columns with the small data frame.

How can I do this in python ?

Answer

I think you can select by loc index and columns of small DataFrame:

dfbig.loc[dfsmall.index, dfsmall.columns]

Sample:

dfbig = pd.DataFrame({'a':[1,2,3,4,5], 'b':[4,7,8,9,4], 'c':[5,0,1,2,4]})
print (dfbig)
   a  b  c
0  1  4  5
1  2  7  0
2  3  8  1
3  4  9  2
4  5  4  4

dfsmall = pd.DataFrame({'a':[4,8], 'c':[0,1]})
print (dfsmall)
   a  c
0  4  0
1  8  1

print (dfbig.loc[dfsmall.index, dfsmall.columns])
   a  c
0  1  5
1  2  0
Comments