给定一个包含“BoolCol”列的DataFrame,我们希望找到其中“BoolCol”值== True的DataFrame的索引

我目前有迭代的方式来做到这一点,这是完美的:

for i in range(100,3000):
    if df.iloc[i]['BoolCol']== True:
         print i,df.iloc[i]['BoolCol']

但这不是熊猫的正确做法。经过一些研究,我目前正在使用以下代码:

df[df['BoolCol'] == True].index.tolist()

这一个给了我一个索引列表,但它们不匹配,当我检查它们时,我这样做:

df.iloc[i]['BoolCol']

结果实际上是假的!!

熊猫的正确做法是什么?


当前回答

简单的方法是在过滤之前重置DataFrame的索引:

df_reset = df.reset_index()
df_reset[df_reset['BoolCol']].index.tolist()

有点俗气,但是很快!

其他回答

如果你只想使用你的dataframe对象一次,使用:

df['BoolCol'].loc[lambda x: x==True].index

我扩展了这个问题,即如何获得行,列和值的所有匹配值?

下面是解决方案:

import pandas as pd
import numpy as np


def search_coordinate(df_data: pd.DataFrame, search_set: set) -> list:
    nda_values = df_data.values
    tuple_index = np.where(np.isin(nda_values, [e for e in search_set]))
    return [(row, col, nda_values[row][col]) for row, col in zip(tuple_index[0], tuple_index[1])]


if __name__ == '__main__':
    test_datas = [['cat', 'dog', ''],
                  ['goldfish', '', 'kitten'],
                  ['Puppy', 'hamster', 'mouse']
                  ]
    df_data = pd.DataFrame(test_datas)
    print(df_data)
    result_list = search_coordinate(df_data, {'dog', 'Puppy'})
    print(f"\n\n{'row':<4} {'col':<4} {'name':>10}")
    [print(f"{row:<4} {col:<4} {name:>10}") for row, col, name in result_list]

输出:

          0        1       2
0       cat      dog        
1  goldfish           kitten
2     Puppy  hamster   mouse


row  col        name
0    1           dog
2    0         Puppy

简单的方法是在过滤之前重置DataFrame的索引:

df_reset = df.reset_index()
df_reset[df_reset['BoolCol']].index.tolist()

有点俗气,但是很快!

首先,当目标列是bool类型时,你可以检查查询(PS:关于如何使用它,请检查链接)

df.query('BoolCol')
Out[123]: 
    BoolCol
10     True
40     True
50     True

在我们通过布尔列过滤原始df之后,我们可以选择索引。

df=df.query('BoolCol')
df.index
Out[125]: Int64Index([10, 40, 50], dtype='int64')

熊猫也有非零,我们只是选择True行的位置,并使用它切片数据帧或索引

df.index[df.BoolCol.values.nonzero()[0]]
Out[128]: Int64Index([10, 40, 50], dtype='int64')

可以使用numpy where()函数完成:

import pandas as pd
import numpy as np

In [716]: df = pd.DataFrame({"gene_name": ['SLC45A1', 'NECAP2', 'CLIC4', 'ADC', 'AGBL4'] , "BoolCol": [False, True, False, True, True] },
       index=list("abcde"))

In [717]: df
Out[717]: 
  BoolCol gene_name
a   False   SLC45A1
b    True    NECAP2
c   False     CLIC4
d    True       ADC
e    True     AGBL4

In [718]: np.where(df["BoolCol"] == True)
Out[718]: (array([1, 3, 4]),)

In [719]: select_indices = list(np.where(df["BoolCol"] == True)[0])

In [720]: df.iloc[select_indices]
Out[720]: 
  BoolCol gene_name
b    True    NECAP2
d    True       ADC
e    True     AGBL4

虽然你并不总是需要index来匹配,但如果你需要:

In [796]: df.iloc[select_indices].index
Out[796]: Index([u'b', u'd', u'e'], dtype='object')

In [797]: df.iloc[select_indices].index.tolist()
Out[797]: ['b', 'd', 'e']