Chethan
Chethan

Reputation: 611

Select the row values of dataframe if row name is present in column name of another dataframe in pandas

If I have df1

df1 = pd.DataFrame({'Col_Name': {0: 'A', 1: 'b', 2: 'c'}, 'X': {0: 12, 1: 23, 2: 223}, 'Z': {0: 42, 1: 33, 2: 28 }})

and df2

df2 = pd.DataFrame({'Col': {0: 'Y', 1: 'X', 2: 'Z'}, 'Low1': {0: 0, 1: 0, 2: 0}, 'High1': {0: 10, 1: 10, 2: 630}, 'Low2': {0: 10, 1: 10, 2: 630}, 'High2': {0: 50, 1: 50, 2: 3000}, 'Low3': {0: 50, 1: 50, 2: 3000}, 'High3': {0: 100, 1: 100, 2: 8500}, 'Low4': {0: 100, 1: 100, 2: 8500}, 'High4': {0: 'np.inf', 1: 'np.inf', 2: 'np.inf'}})

Select the row values of df2 if row is present in column name of df1.

Expected Output: df3

df3 = pd.DataFrame({'Col': {0: 'X', 1: 'Z'}, 'Low1': {0: 0, 1: 0}, 'High1': {0: 10, 1: 630}, 'Low2': {0: 10, 1: 630}, 'High2': {0: 50, 1: 3000}, 'Low3': {0: 50, 1: 3000}, 'High3': {0: 100, 1: 8500}, 'Low4': {0: 100, 1: 8500}, 'High4': {0: 'np.inf', 1: 'np.inf'}})

How to do it?

Upvotes: 1

Views: 287

Answers (2)

Ran Cohen
Ran Cohen

Reputation: 751

you can drop the non-relevant col and use the other columns...

df3 = df2[df2['Col'].isin(list(df1.drop('Col_Name',axis=1).columns))]

enter image description here

Upvotes: 1

Benedictanjw
Benedictanjw

Reputation: 838

You can pass a boolean list to select the rows of df2 that you want. This list can be created by looking at each value in the Col column and asking if the value is in the columns of df1

df3 = df2[[col in df1.columns for col in df2['Col']]]

Upvotes: 1

Related Questions