列"BoolCol"を持つDataFrameが与えられたときに、"BoolCol"==Trueを持つDataFrameのインデックスを求めます。
私は現在、反復法でそれを行っていますが、これは完璧に動作します。
for i in range(100,3000):
if df.iloc[i]['BoolCol']== True:
print i,df.iloc[i]['BoolCol']
しかし、これは正しいpanda'のやり方ではありません。 いろいろ調べた結果、現在はこのコードを使っています。
df[df['BoolCol'] == True].index.tolist()
このコードはインデックスのリストを与えてくれますが、実際にチェックしてみると一致しません。
df.iloc[i]['BoolCol']
結果はなんとFalse!
正しいPandasの方法はどれでしょうか?
df.iloc[i]は
dfの
ith行を返します。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')
であれば、iloc
の代わりにloc
を使って行を選択することができます。
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
をチェックすることができます(追記:使い方は リンク を参照してください)。
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')