Python Pandas: Iegūt to rindu indeksu, kuru sleja atbilst noteiktai vērtībai

Ja ir dots DataFrame ar kolonnu "BoolCol", mēs vēlamies atrast DataFrame indeksus, kuros "BoolCol" == True.

Pašlaik man ir iterācijas veids, kā to izdarīt, kas darbojas perfekti:

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

Bet tas nav pareizais panda veids, kā to darīt. Pēc izpētes es pašlaik izmantoju šo kodu:

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

Tas dod man indeksu sarakstu, bet tie nesakrīt, kad es tos pārbaudu, veicot:

df.iloc[i]['BoolCol']

Rezultāts faktiski ir False!!

Kurš būtu pareizākais Pandas veids, kā to izdarīt?

Risinājums

df.iloc[i] atgriež df rindiņu. i neatsaucas uz indeksa etiķeti, i ir indekss, kura pamatā ir 0.

Turpretī atribūts index atgriež faktiskās indeksu etiķetes, nevis skaitliskos rindu indeksus:

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

vai līdzvērtīgi,

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

Jūs varat redzēt atšķirību diezgan skaidri, spēlējoties ar DataFrame ar indeksu, kas nav noklusējuma indekss, kurš nav vienāds ar rindas skaitlisko pozīciju:

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]

Ja vēlaties izmantot indeksu,

In [56]: idx = df.index[df['BoolCol']]

In [57]: idx
Out[57]: Int64Index([10, 40, 50], dtype='int64')

tad rindas var atlasīt, izmantojot loc, nevis iloc:

In [58]: df.loc[idx]
Out[58]: 
   BoolCol
10    True
40    True
50    True

[3 rows x 1 columns]

Ņemiet vērā, ka loc var pieņemt arī boolean masīvus:

In [55]: df.loc[df['BoolCol']]
Out[55]: 
   BoolCol
10    True
40    True
50    True

[3 rows x 1 columns]

Ja jums ir boolean masīvs mask un ir nepieciešamas kārtas indeksu vērtības, tās var aprēķināt, izmantojot np.flatnonzero:

In [110]: np.flatnonzero(df['BoolCol'])
Out[112]: array([0, 3, 4])

Izmantojiet df.iloc, lai atlasītu rindas pēc kārtas indeksa:

In [113]: df.iloc[np.flatnonzero(df['BoolCol'])]
Out[113]: 
   BoolCol
10    True
40    True
50    True
Komentāri (8)

To var izdarīt, izmantojot funkciju 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

Lai gan jums ne vienmēr ir nepieciešams indekss, lai atrastu atbilstību, bet gadījumā, ja nepieciešams:

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']
Komentāri (0)

Vispirms varat pārbaudīt query, ja mērķa kolonnas tips ir bool (PS: par to, kā to izmantot, lūdzu, skatiet saite ).

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

Pēc tam, kad mēs filtrējam sākotnējo df pēc "Boolean" slejas, mēs varam izvēlēties indeksu .

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

Arī pandas ir nonzero, mēs vienkārši izvēlamies True rindas pozīciju un, izmantojot to, sagriežam DataFrame vai index.

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