Sash7
Sash7

Reputation: 123

How to find the subset of a dataframe, given a specific index and a specific value?

I have a huge dataframe to work with. I am having difficulties in figuring out how to get the subset of the dataframe given a specific index and only such columns should be selected having a specific value.

My objective can be illustrated as follows:

data = {'A': [5,6,9,8,3,2,4,1],
        'B': [1,5,3,4,2,1,1,1],
        'C': [1,0,0,1,3,4,5,3],
        'D': [5,6,9,8,7,1,1,1]
        }

df = pd.DataFrame(data)
df

I would like to have a subset of DataFrame where index is 5 and the specific value is 1.

Desired Output:

  B D
------
5 1 1

I used the following command to get the index=5 values.

df.loc[df.index==5, df.columns]

I tried to refer to related questions, but could not come up with a solution. Please do help.

Upvotes: 0

Views: 45

Answers (1)

Onyambu
Onyambu

Reputation: 79228

pd.DataFrame(data.loc[5, data.iloc[5,:]==1]).T
Out[]: 
   B  D
5  1  1

Upvotes: 1

Related Questions