1

If you have a df:

  apple   banana   carrot    
a   1       2        3
b   2       3        1
c   0       0        1

To find the index for the columns where a cell is equal to 0 is df[df['apple']==0].index but can you transpose this so you find the index of row c where it is 0?

Basically I need to drop the columns where c==0 and would like to do this in one line by row rather than by each column.

2 Answers 2

1

If want test row c and get all columns if 0:

c = df.columns[df.loc['c'] == 0]
print (c)
Index(['apple', 'banana'], dtype='object')

If want test all rows:

c1 = df.columns[df.eq(0).any()]
print (c1)
Index(['apple', 'banana'], dtype='object')

If need remove columns if 0 in any row:

df = df.loc[:, df.ne(0).all()]
print (df)
   carrot
a       3
b       1
c       1

Detail/explanation:

First compare all values of DataFrame by ne (!=):

print (df.ne(0))
   apple  banana  carrot
a   True    True    True
b   True    True    True
c  False   False    True

Then get all rows if all True rows:

print (df.ne(0).all())
apple     False
banana    False
carrot     True
dtype: bool

Last filter by DataFrame.loc:

print (df.loc[:, df.loc['c'].ne(0)])
   carrot
a       3
b       1
c       1

If need test only c row solution is similar, only first select c row by loc and omit all:

df = df.loc[:, df.loc['c'].ne(0)]
Sign up to request clarification or add additional context in comments.

Comments

1

Yes you can, df.T[df.T['c']==0]

Comments

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.