[python] Python Pandas : 특정 값과 일치하는 열의 색인을 가져옵니다.

“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']

결과는 실제로 거짓입니다!

이 작업을 수행하는 올바른 팬더 방법은 무엇입니까?



답변

df.iloc[i]ith행을 반환합니다 df. i인덱스 레이블을 나타내지 않고 i0 기반 인덱스입니다.

대조적으로, 속성 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']


답변

간단한 방법은 필터링하기 전에 DataFrame의 인덱스를 재설정하는 것입니다.

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

조금 해 키지 만 빠르다!


답변

먼저 query대상 열이 유형인지 확인하십시오 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')

또한 팬더는 행 nonzero위치 를 선택하고 True슬라이스를 사용하여 DataFrame또는index

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


답변

데이터 프레임 객체를 한 번만 사용하려면 다음을 사용하십시오.

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


답변

나는이에를 얻는 방법이다이 질문을 확장 row, column그리고 value모든 일치 값?

여기 해결책이 있습니다 :

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


답변