how to subset df based on value condition in python

To subset a pandas DataFrame based on a value condition, you can use boolean indexing. Here's an example:

main.py
import pandas as pd

# create a sample dataframe
df = pd.DataFrame({'name': ['Alice', 'Bob', 'Charlie', 'David'],
                   'age': [25, 30, 35, 40]})

# subset the dataframe where age is greater than 30
df_subset = df[df['age'] > 30]

print(df_subset)
261 chars
11 lines

This will output:

main.py
      name  age
2  Charlie   35
3    David   40
48 chars
4 lines

In this example, we use boolean indexing to subset the DataFrame df to create df_subset where the age column is greater than 30.

related categories

gistlibby LogSnag