Reputation: 4521
I would like to get the integer positions of rows in a pandas series, where the series contains specific values, or for the positions in an boolean indexer, where the value is True.
If I have the following dataframe, I would like to get the integer positions of the True
values in column label
:
import pandas as pd
data=dict()
data["col_0"]=[-0.2518508748588564, -0.6339192005025384, -0.6938892242609978, 2.4470042529183402, 0.8977665869071174]
data["label"]=[False, False, True, False, True]
df2= pd.DataFrame(data)
I could of course do that like below, but it seems a big awkward to me and I wonder, if there is a cleaner way to do this (especially without a reset_index, but the solution should work no matter what index labels are used in the original dataframe):
ser= df2['label']
new_ser= ser.reset_index(drop=True)
new_ser.index[new_ser].to_list()
The result is of course [2, 4]
.
Upvotes: 1
Views: 140
Reputation: 16683
You can use:
np.flatnonzero(df2['label'])
data=dict()
data["col_0"]=[-0.2518508748588564, -0.6339192005025384, -0.6938892242609978, 2.4470042529183402, 0.8977665869071174]
data["label"]=[False, False, True, False, True]
df2= pd.DataFrame(data)
np.flatnonzero(df2['label'])
Out[1]: array([2, 4], dtype=int64)
That makes it an np.array. To make a list, use:
[*np.flatnonzero(df2['label'])]
Out[2]: [2, 4]
Upvotes: 1