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?
1 Resposta
- 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]