如何在pandas索引器中获取True条目的整数位置



我想获取panda系列中行的整数位置,其中该系列包含特定值,或者获取布尔索引器中的位置,其中值为True。

如果我有以下数据帧,我想获得列label:中True值的整数位置

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)

我当然可以像下面这样做,但这对我来说似乎很尴尬,我想知道是否有更干净的方法来做到这一点(尤其是在没有reset_index的情况下,但无论原始数据帧中使用什么索引标签,解决方案都应该起作用(:

ser= df2['label']
new_ser= ser.reset_index(drop=True)
new_ser.index[new_ser].to_list()

结果当然是[2, 4]

您可以使用:

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)

这使它成为一个np.array。要列出一个列表,请使用:

[*np.flatnonzero(df2['label'])]
Out[2]: [2, 4]

相关内容

最新更新