0

How do we select columns based on some conditions in a DataFrame in python?

I have learned how to select rows based on conditions, like this: import pandas as pd data = { 'ages': [14, 18, 24, 42], 'heights': [165, 180, 176, 184] } df = pd.DataFrame(data, index=['James', 'Bob', 'Amy', 'Dave']) print(df[(df['ages']>18) & (df['heights']>180)]) In the codes above, the conditions for selecting rows are age being larger than 18 and height being larger than 180. But if I want to select some columns based on some conditions, how do I do that?

21st Jan 2022, 2:10 PM
jklmy
1 Antwort
- 1
Based on your code. Do this: columns = ['column I want 1', 'column I want 2'] # column name should be your real column name like ages or heights df_you_want = df[(df['ages']>18) & (df['heights']>180)][columns]
25th Jan 2022, 12:47 PM
Aaron Yang
Aaron Yang - avatar