Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep columns based on a given row values

Here how the datalooks like in df dataframe:

        A   B   C   D
0.js    2   1   1  -1
1.js    3  -5   1  -4
total   5  -4   2  -5

And I would get new dataframe df1:

        A     C
0.js    2     1
1.js    3     1
total   5     2

So basically it should look like this: df1 = df[df["total"] > 0] but it should filter on row instead of column and I can't figure it out..

like image 364
J Oderberg Avatar asked Feb 05 '19 20:02

J Oderberg


People also ask

How do you select columns based on row values?

You can just select the columns with, for instance, a<-dat[,(dat[1,]) == 1] ; the only trick is re-setting the column names when you end up extracting a single column.


1 Answers

You want to use .loc[:, column_mask] i.e.

In [11]: df.loc[:, df.sum() > 0]
Out[11]:
       A  C
total  5  2

# or

In [12]: df.loc[:, df.iloc[0] > 0]
Out[12]:
       A  C
total  5  2
like image 132
Andy Hayden Avatar answered Oct 23 '22 12:10

Andy Hayden