티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Python Pandas: Get index of rows where column matches certain value

Python Pandas: 특정 값과 일치하는 열의 행 인덱스 가져오기

 문제 내용 

Given a DataFrame with a column "BoolCol", we want to find the indexes of the DataFrame in which the values for "BoolCol" == True

"BoolCol" 열(column)을 가진 DataFrame이 주어졌을 때, "BoolCol" 값이 True인 DataFrame의 인덱스(index)를 찾으려고 합니다.

 

I currently have the iterating way to do it, which works perfectly:

현재 반복문을 사용해 문제를 해결하는 코드가 있는데, 아래와 같이 작동합니다.
for i in range(100,3000):     if df.iloc[i]['BoolCol']== True:          print i,df.iloc[i]['BoolCol'] 

 

But this is not the correct pandas way to do it. After some research, I am currently using this code:

하지만 이는 올바른 Pandas 방법이 아닙니다. 몇 가지 조사 후, 저는 현재 이 코드를 사용하고 있습니다.
df[df['BoolCol'] == True].index.tolist() 

 

This one gives me a list of indexes, but they don't match, when I check them by doing:

위 코드는 인덱스의 리스트를 반환하지만, 다음과 같이 확인해보면 일치하지 않습니다.
df.iloc[i]['BoolCol'] 

 

The result is actually False!!

결과는 실제로 False입니다!

 

Which would be the correct pandas way to do this?

이를 수행하는 올바른 Pandas 방법은 무엇인가요?

 

 

 

 높은 점수를 받은 Solution 

df.iloc[i] returns the ith row of df. i does not refer to the index label, i is a 0-based index.

df.iloc[i]는 df의 i번째 행(row)을 반환합니다. 여기서 i는 0부터 시작하는 인덱스를 의미합니다. 따라서 i는 인덱스 라벨이 아닌, 0부터 시작하는 숫자 인덱스입니다.

 

In contrast, the attribute index returns actual index labels, not numeric row-indices:

반면에, 속성 index는 실제 인덱스 라벨을 반환하며 숫자로 된 행 인덱스는 아닙니다.
df.index[df['BoolCol'] == True].tolist() 

 

or equivalently,

또는 동등하게,
df.index[df['BoolCol']].tolist() 

 

You can see the difference quite clearly by playing with a DataFrame with a non-default index that does not equal to the row's numerical position:

행의 숫자 위치와 같지 않은 기본 인덱스가 아닌 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] 

 


 

If you want to use the index,

만약 index를 사용하고 싶다면,
In [56]: idx = df.index[df['BoolCol']]  In [57]: idx Out[57]: Int64Index([10, 40, 50], dtype='int64') 

 

then you can select the rows using loc instead of iloc:

만약 인덱스를 사용하고 싶다면, iloc 대신 loc를 사용하여 행을 선택할 수 있습니다.
In [58]: df.loc[idx] Out[58]:     BoolCol 10    True 40    True 50    True  [3 rows x 1 columns] 

 


 

Note that loc can also accept boolean arrays:

참고로 loc는 불리언 배열도 허용한다는 것에 주목하자.
In [55]: df.loc[df['BoolCol']] Out[55]:     BoolCol 10    True 40    True 50    True  [3 rows x 1 columns] 

 


 

If you have a boolean array, mask, and need ordinal index values, you can compute them using np.flatnonzero:

만약 boolean 배열인 mask를 가지고 있고, 순서형 인덱스 값을 필요로 한다면 np.flatnonzero를 사용하여 계산할 수 있습니다.
In [110]: np.flatnonzero(df['BoolCol']) Out[112]: array([0, 3, 4]) 

 

Use df.iloc to select rows by ordinal index:

df.iloc을 사용하여 순서 인덱스로 행을 선택하세요.
In [113]: df.iloc[np.flatnonzero(df['BoolCol'])] Out[113]:     BoolCol 10    True 40    True 50    True 

 

 

 가장 최근 달린 Solution 

If you want to use your dataframe object only once, use:

만약 DataFrame 객체를 한 번만 사용하려면 다음을 사용하세요:
df['BoolCol'].loc[lambda x: x==True].index 

 

 

출처 : https://stackoverflow.com/questions/21800169/python-pandas-get-index-of-rows-where-column-matches-certain-value

반응형
댓글
공지사항
최근에 올라온 글