Reputation: 167
I am trying to select all columns of a dataframe(df) into a new dataframe where the value of the first row is ==0.
df=
a b c d
0 1 0 3 0
1 2 7 2 2
2 3 5 2 1
new_df:
b d
0 0 0
1 7 2
2 5 1
It feels like a simple task but I am completly stuck in finding something that works. Thanks in advance!
Upvotes: 2
Views: 610
Reputation: 71570
Or try loc
with iloc
:
>>> df.loc[:, df.iloc[0].eq(0)]
b d
0 0 0
1 7 2
2 5 1
>>>
This will select the columns where the first row is 0.
Or try with T
:
>>> df.T[df.T.eq(0).any(1)].T
b d
0 0 0
1 7 2
2 5 1
>>>
Upvotes: 1
Reputation: 862611
Use first DataFrame.loc
with :
for select all rows and columns by condition - compare first row:
df1 = df.loc[:, df.iloc[0] == 0]
Or compare row with label=0
, obviously first too:
df1 = df.loc[:, df.loc[0].eq(0)]
print (df1)
b d
0 0 0
1 7 2
2 5 1
Upvotes: 3