매번 찾기 귀찮아서 모아두는 개발팁

[Python/Pandas] 다중 조건으로 데이터 행 추출하기(indexing with multidimensional key)

archive-er 2023. 3. 2. 11:37

우선 일반적으로 데이터프레임에서 조건(단일조건)에 맞는 행 추출하는 법

data = data.loc[data["column_name"] == condition]
# data["column_name"] == condition 내의 조건을 필요에 맞게 수정

 

그리고 데이터프레임에서 특정 열만 추출하는 법

column_names = ["col_name1", "col_name2"]
items = data.loc[:, column_names]

 

이 두 개를 섞어서 다중 조건을 이용해 필요한 행을 추출하면 될 것 같은데?

column_names = ["col_name1", "col_name2"]
conditions = [1, 2]
data = data.loc[data[:, column_names] == conditions]

어림없지

ValueError: Cannot index with multidimensional key

대충 다중 키로는 인덱싱하지 말란 말이 뜬다

근데 난 다중키로 인덱싱을 해야하는데?

 

이것저것 해보다가 안돼서 결국 구글링해보니

conditions = (
	data["col_name1"] == 1 &
    	data["col_name2"] == 2
    )
data = data.loc[conditions]

로 하면 된다고 한다! 우와!

 

여기서 끝났다면 이걸 아카이빙하러 오진 않았을 것이다

TypeError: Cannot perform 'rand_' with a dtyped [object] array and scalar of type [bool]

뭐라는지...존나...모르겠음...

 

그래서 냅다 구글링함

conditions = (
	(data["col_name1"] == 1) &
    	(data["col_name2"] == 2)
    )
data = data.loc[conditions]

괄호로 감싸면 된단다!(실제로 됨)

 

왜 안되다가 되는건지는 모르겠음

높은 확률로 연산자 우선순위 문제일거같긴 한데 일단 됐으니 만족하기로 함

 

출처:

https://stackoverflow.com/questions/60654781/typeerror-cannot-perform-rand-with-a-dtyped-float64-array-and-scalar-of-ty

 

TypeError: Cannot perform 'rand_' with a dtyped [float64] array and scalar of type [bool]

I ran a command in python pandas as follows: q1_fisher_r[(q1_fisher_r['TP53']==1) & q1_fisher_r[(q1_fisher_r['TumorST'].str.contains(':1:'))]] I got following error: TypeError: Cannot perform '

stackoverflow.com

의 두 번째 답변