how to get indexex of subsetted dataframe based on a conditon in python

You can use boolean indexing to subset the dataframe based on a condition and then get the index values of the resulting subset.

Here's an example:

main.py
import pandas as pd

# create a sample dataframe
df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [5, 6, 7, 8]})

# subset the dataframe based on a condition
subset = df[df['a'] > 2]

# get the index values of the resulting subset
subset_index = subset.index

print(subset_index)
274 chars
13 lines

Output:

main.py
Int64Index([2, 3], dtype='int64')
34 chars
2 lines

In this example, we first create a sample dataframe with two columns 'a' and 'b'. We then subset the dataframe based on the condition df['a'] > 2, which selects all rows where column 'a' is greater than 2. Finally, we get the index values of the resulting subset using the .index attribute of the dataframe.

related categories

gistlibby LogSnag