Minh-Long Luu
Minh-Long Luu

Reputation: 2731

Pandas: new DataFrame from another DataFrame with conditions

I have the following DataFrame:

A   |   B   |   C   |   D
1   |   2   |   4   |   5
0   |   2   |   5   |   2
1   |   1   |   2   |   1

I want a new DataFrame that only takes column B, C, but only where A == 1. This is what I want:

B   |   C
2   |   4
1   |   2

Although I can first filter the condition where A == 1, then take only column B, C from the result, but is the a more "pythonic" way to do it?

Upvotes: 1

Views: 156

Answers (1)

jezrael
jezrael

Reputation: 862441

Use DataFrame.loc with mask and columns names in list:

df1 = df.loc[df.A == 1, ['B','C']]

Upvotes: 2

Related Questions