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
레이블인 인스라벨참조않습하다니지을덱,를 참조하지 않습니다.i
는 0 기반 인덱스입니다.
반대로 속성은 숫자 행 인덱스가 아닌 실제 인덱스 레이블을 반환합니다.
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')
그런 다음 다음 대신 를 사용하여 행을 선택할 수 있습니다.
In [58]: df.loc[idx]
Out[58]:
BoolCol
10 True
40 True
50 True
[3 rows x 1 columns]
에서는 부울 배열도 사용할 수 있습니다.
In [55]: df.loc[df['BoolCol']]
Out[55]:
BoolCol
10 True
40 True
50 True
[3 rows x 1 columns]
부울 배열이 있고 순서형 인덱스 값이 필요한 경우 다음을 사용하여 계산할 수 있습니다.
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를 사용하여 수행할 수 있는 기능은 다음과 같습니다.
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']
데이터 프레임 개체를 한 번만 사용하려면 다음을 사용합니다.
df['BoolCol'].loc[lambda x: x==True].index
간단한 방법은 필터링하기 전에 데이터 프레임의 인덱스를 재설정하는 것입니다.
df_reset = df.reset_index()
df_reset[df_reset['BoolCol']].index.tolist()
좀 촌스럽긴 한데, 빠르네요!
먼저 확인할 수 있습니다.query
이 type 대상열유때일인 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')
팬더는 또한판들은다은들판다▁have를 가지고 있습니다.nonzero
우리는 단지 위치를 선택할 뿐입니다.True
노를 젓고 그것을 사용하여 슬라이스합니다.DataFrame
또는index
df.index[df.BoolCol.values.nonzero()[0]]
Out[128]: Int64Index([10, 40, 50], dtype='int64')
은 다방법다같음다습니과은른을 사용하는 것입니다.pipe()
의 BoolCol
성능 측면에서 이는 다음을 사용하는 표준 인덱싱만큼이나 효율적입니다.[]
.1
df['BoolCol'].pipe(lambda x: x.index[x])
이것은 특히 다음과 같은 경우에 유용합니다.BoolCol
실제로는 다중 비교의 결과이며 모든 방법을 파이프라인에 넣으려면 방법 체인을 사용하려고 합니다.
들어 행 다음과 같이 .NumCol
이 0 0.5보다 큽니다.BoolCol
값은 True이고 곱은 다음과 같습니다.NumCol
그리고.BoolCol
값이 0보다 크므로 다음을 통해 식을 평가할 수 있습니다.eval()
와 콜pipe()
인덱스의 2인덱싱을 수행할 결과입니다.
df.eval("NumCol > 0.5 and BoolCol and NumCol * BoolCol >0").pipe(lambda x: x.index[x])
다음 벤치마크에서는 2,000만 행(평균적으로 필터링된 행의 절반)이 있는 데이터 프레임을 사용하여 인덱스를 1검색했습니다.메소드 체인 연결 방법pipe()
다른 효율적인 옵션에 비해 매우 잘 작동합니다.
n = 20_000_000
df = pd.DataFrame({'NumCol': np.random.rand(n).astype('float16'),
'BoolCol': np.random.default_rng().choice([True, False], size=n)})
%timeit df.index[df['BoolCol']]
# 181 ms ± 2.47 ms per loop (mean ± std. dev. of 10 runs, 1000 loops each)
%timeit df['BoolCol'].pipe(lambda x: x.index[x])
# 181 ms ± 1.08 ms per loop (mean ± std. dev. of 10 runs, 1000 loops each)
%timeit df['BoolCol'].loc[lambda x: x].index
# 297 ms ± 7.15 ms per loop (mean ± std. dev. of 10 runs, 1000 loops each)
벤치마크에 대해 에서 설명한 것과 동일한 방법으로 구성된 2,000마일 데이터 프레임의 경우, 여기서 제안한 방법이 가장 빠른 옵션임을 알 수 2있습니다.비트 연산자 체인보다 더 나은 성능을 발휘합니다. 왜냐하면 설계상,eval()
벡터화된 Python 작업보다 큰 데이터 프레임에서 여러 작업을 더 빠르게 수행하고 메모리 효율성이 보다 높습니다.query()
와는 달리query()
,eval().pipe(...)
인덱스를 가져오기 위해 분할된 데이터 프레임의 복사본을 만들 필요가 없습니다.
나는 어떻게 그것을 얻는지에 대한 이 질문을 확장했습니다.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
우리가 관심 있는 알려진 인덱스 후보의 경우 전체 열을 확인하지 않는 더 빠른 방법은 다음과 같습니다.
np.array(index_slice)[np.where(df.loc[index_slice]['column_name'] >= threshold)[0]]
전체 비교:
import pandas as pd
import numpy as np
index_slice = list(range(50,150)) # know index location for our inteterest
data = np.zeros(10000)
data[(index_slice)] = np.random.random(len(index_slice))
df = pd.DataFrame(
{'column_name': data},
)
threshold = 0.5
%%timeit
np.array(index_slice)[np.where(df.loc[index_slice]['column_name'] >= threshold)[0]]
# 600 µs ± 1.21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%%timeit
[i for i in index_slice if i in df.index[df['column_name'] >= threshold].tolist()]
# 22.5 ms ± 29.1 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
작동 방식은 다음과 같습니다.
# generate Boolean satisfy condition only in sliced column
df.loc[index_slice]['column_name'] >= threshold
# convert Boolean to index, but start from 0 and increment by 1
np.where(...)[0]
# list of index to be sliced
np.array(index_slice)[...]
참고: 주의할 점은np.array(index_slice)
로 대신할 수 없음df.index
때문에np.where(...)[0]
색인화start from 0 and increment by 1
하지만 당신은 다음과 같은 것을 만들 수 있습니다.df.index[index_slice]
그리고 행 수가 적은 상태에서 한 번만 수행하면 이 작업을 수행할 가치가 없다고 생각합니다.
언급URL : https://stackoverflow.com/questions/21800169/python-pandas-get-index-of-rows-where-column-matches-certain-value
'programing' 카테고리의 다른 글
마이크로소프트를 구성합니다.사용자 이름으로 전자 메일 주소를 허용하는 AsNet.Identity (0) | 2023.05.27 |
---|---|
express.js에서 HTTPS 사용 (0) | 2023.05.22 |
Excel 오류 1004 "WorksheetFunction 클래스의 속성...을(를) 가져올 수 없습니다."가 일관성 없이 나타납니다. (0) | 2023.05.22 |
ReSharper를 사용하여 솔루션에서 사용되지 않는 메서드를 나열하려면 어떻게 해야 합니까? (0) | 2023.05.22 |
다른 Git Merge 전략을 언제 사용하시겠습니까? (0) | 2023.05.22 |