给定一个有列"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']
结果居然是假的!!
哪种方式才是正确的Pandas方式?
df.iloc[i]
返回df
的第
一行'。i'不是指索引标签,
i'是一个基于0的索引。
相反,属性index
返回实际的索引标签,而不是数字的行指数。
df.index[df['BoolCol'] == True].tolist()
或等价的。
df.index[df['BoolCol']].tolist()
你可以通过玩一个具有以下特征的DataFrame来很清楚地看到区别 非默认索引不等于行的数字位置的数据框架。
df = pd.DataFrame({'BoolCol': [True, False, False, True, True]},
index=[10,20,30,40,50])
In [53]: df
Out[53]:
BoolCol
10 True
20 False
30 False
40 True
50 True
[5 rows x 1 columns]
In [54]: df.index[df['BoolCol']].tolist()
Out[54]: [10, 40, 50]
如果你想使用该索引。
In [56]: idx = df.index[df['BoolCol']]
In [57]: idx
Out[57]: Int64Index([10, 40, 50], dtype='int64')
那么你可以使用loc
而不是iloc
来选择行。
In [58]: df.loc[idx]
Out[58]:
BoolCol
10 True
40 True
50 True
[3 rows x 1 columns]
注意,loc
也可以接受布尔数组。
In [55]: df.loc[df['BoolCol']]
Out[55]:
BoolCol
10 True
40 True
50 True
[3 rows x 1 columns]
如果你有一个布尔数组,mask
,并且需要序数索引值,你可以使用np.flatnonzero
来计算。
In [110]: np.flatnonzero(df['BoolCol'])
Out[112]: array([0, 3, 4])
使用df.iloc
按序数索引选择行。
In [113]: df.iloc[np.flatnonzero(df['BoolCol'])]
Out[113]:
BoolCol
10 True
40 True
50 True
可以用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
虽然你并不总是需要索引来进行匹配,但如果你需要的话。
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']
首先,当目标列是 "bool "类型时,你可以检查 "query"(PS:关于如何使用它,请查看link )。
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')
pandas也有 "nonzero",我们只需选择 "True "行的***位置,然后用它来切分 "DataFrame "或 "index"。
df.index[df.BoolCol.nonzero()[0]]
Out[128]: Int64Index([10, 40, 50], dtype='int64')