subset dataframe based on index value in python

To subset a dataframe based on index value, you can use the .loc accessor.

Here's an example:

main.py
import pandas as pd

# Create a sample dataframe
df = pd.DataFrame({
    'name': ['Alice', 'Bob', 'Charlie', 'Dave'],
    'age': [25, 30, 35, 40],
    'salary': [50000, 60000, 70000, 80000]
})

# Set the 'name' column as the index
df.set_index('name', inplace=True)

# Subset the dataframe based on index value
subset_df = df.loc['Bob':'Dave']

# Print the subset dataframe
print(subset_df)
391 chars
18 lines

In the code above, we first create a sample dataframe with a 'name', 'age', and 'salary' column. We then set the 'name' column as the index. To subset the dataframe based on index value, we use the .loc accessor and pass in the range of index values we are interested in (in this case, 'Bob' to 'Dave'). Finally, we print the subset dataframe.

The output will be:

main.py
         age  salary
name               
Bob       30   60000
Charlie   35   70000
Dave      40   80000
104 chars
6 lines

related categories

gistlibby LogSnag