[Python] How to get the integer positions of the True entries in a pandas indexer

Discussão em 'Python' iniciado por Stack, Maio 22, 2025.

  1. Stack

    Stack Membro Participativo

    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].

    Continue reading...

Compartilhe esta Página