티스토리 뷰

반응형

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

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

 

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

How to check if a column exists in Pandas

판다스에 열이 있는지 확인하는 방법

 문제 내용 

How do I check if a column exists in a Pandas DataFrame df?

판다스 데이터프레임 df에 열이 있는지 어떻게 확인하나요?
   A   B    C
0  3  40  100
1  6  30  200

 

How would I check if the column "A" exists in the above DataFrame so that I can compute:

계산할 수 있도록 위의 데이터프레임에 "A" 열이 있는지 어떻게 확인하나요:
df['sum'] = df['A'] + df['C']

 

And if "A" doesn't exist:

그리고 "A"가 존재하지 않는 경우:
df['sum'] = df['B'] + df['C']

 

 

 높은 점수를 받은 Solution 

This will work:

이 방법은 다음과 같습니다:
if 'A' in df:

 

But for clarity, I'd probably write it as:

하지만 명확하게 하기 위해서, 저는 아마 다음과 같이 쓸 것 같아요:
if 'A' in df.columns:

 

 

 가장 최근 달린 Solution 

You can also call isin() on the columns to check if it exists and call any() on the result to reduce it to a single boolean value1:

열에 대해 isin()을 호출하여 열이 존재하는지 확인하고 결과에 대해 any()를 호출하여 단일 부울 값(아래 1: 참고)으로 줄일 수도 있습니다:
if df.columns.isin(['A', 'C']).any():
    # do something

 

To check if a column name is not present, you can use the not operator in the if-clause:

열 이름이 없는지 확인하려면 if-clause에서 not 연산자를 사용할 수 있습니다:
if 'A' not in df:
    # do something

 

or along with the isin().any() call.

또는 isin().any() 호출과 함께.
if not df.columns.isin(['A', 'C']).any():
    # do something

1: isin() call on the columns returns a boolean array whose values are True if it's either A or C and False otherwise. The truth value of an array is ambiguous, so any() call reduces it to a single True/False value.

1: 열에 대한 isin() 호출은 값이 A 또는 C이면 True이고 그렇지 않으면 False인 부울 배열을 반환합니다. 배열의 진리값은 모호하므로 any() 호출은 단일 True/False 값으로 줄입니다.

 

 

 

출처 : https://stackoverflow.com/questions/24870306/how-to-check-if-a-column-exists-in-pandas

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