티스토리 뷰

반응형

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

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

 

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

How to check whether a pandas DataFrame is empty?

pandas dataframe이 비어 있는지 확인하는 방법은?

 문제 내용 

How to check whether a pandas DataFrame is empty? In my case I want to print some message in terminal if the DataFrame is empty.

판다스 데이터프레임이 비어 있는지 확인하는 방법은 무엇인가요? 제 경우에는 데이터프레임이 비어 있으면 터미널에서 메시지를 출력하고 싶습니다.

 

 

 

 높은 점수를 받은 Solution 

You can use the attribute df.empty to check whether it's empty or not:

데이터프레임이 비어 있는지 확인하려면 df.empty 속성을 사용할 수 있습니다:
if df.empty:
    print('DataFrame is empty!')

 

Source: Pandas Documentation

출처: 판다스 문서

 

 

 

 가장 최근 달린 Solution 

To see if a dataframe is empty, I argue that one should test for the length of a dataframe's columns index:

데이터프레임이 비어 있는지 확인하려면, 데이터프레임의 컬럼 인덱스 길이를 테스트하는 것이 좋다고 생각합니다:
if len(df.columns) == 0: 1

 

Reason:

이유:

 

According to the Pandas Reference API, there is a distinction between:

판다스 참조 API에 따르면 다음과 같은 차이점이 있습니다:

 

  • an empty dataframe with 0 rows and 0 columns
  • an empty dataframe with rows containing NaN hence at least 1 column
0개의 행과 0개의 열이 있는 빈 데이터프레임
NaN이 있는 행이 적어도 1개 있는 빈 데이터프레임

 

Arguably, they are not the same. The other answers are imprecise in that df.empty, len(df), or len(df.index) make no distinction and return index is 0 and empty is True in both cases.

아마도 이 둘은 동일하지 않습니다. 다른 답변들은 df.empty, len(df), 또는 len(df.index)이 구별하지 않으며, 두 경우 모두 인덱스는 0이고 비어 있음은 참입니다.

 

Examples

예제

 

Example 1: An empty dataframe with 0 rows and 0 columns

예제 1: 0개의 행과 0개의 열이 있는 빈 데이터프레임
In [1]: import pandas as pd
        df1 = pd.DataFrame()
        df1
Out[1]: Empty DataFrame
        Columns: []
        Index: []

In [2]: len(df1.index)  # or len(df1)
Out[2]: 0

In [3]: df1.empty
Out[3]: True

 

Example 2: A dataframe which is emptied to 0 rows but still retains n columns

예제 2: 행이 0개로 줄어들었지만 여전히 n개의 열이 있는 데이터프레임
In [4]: df2 = pd.DataFrame({'AA' : [1, 2, 3], 'BB' : [11, 22, 33]})
        df2
Out[4]:    AA  BB
        0   1  11
        1   2  22
        2   3  33

In [5]: df2 = df2[df2['AA'] == 5]
        df2
Out[5]: Empty DataFrame
        Columns: [AA, BB]
        Index: []

In [6]: len(df2.index)  # or len(df2)
Out[6]: 0

In [7]: df2.empty
Out[7]: True

 

Now, building on the previous examples, in which the index is 0 and empty is True. When reading the length of the columns index for the first loaded dataframe df1, it returns 0 columns to prove that it is indeed empty.

이전 예제를 바탕으로, 로드된 첫 번째 데이터프레임 df1에서 열 길이를 읽으면, 실제로 비어 있음을 증명하기 위해 0열을 반환합니다.
In [8]: len(df1.columns)
Out[8]: 0

In [9]: len(df2.columns)
Out[9]: 2

 

Critically, while the second dataframe df2 contains no data, it is not completely empty because it returns the amount of empty columns that persist.

그러나 두 번째 데이터프레임 df2는 데이터가 없지만, 여전히 비어 있지 않습니다. 이는 지속되는 빈 열의 수를 반환하기 때문입니다.

 

Why it matters

왜 중요한가

 

Let's add a new column to these dataframes to understand the implications:

이 데이터프레임에 새로운 열을 추가하면 어떻게 되는지 살펴보겠습니다:
# As expected, the empty column displays 1 series
In [10]: df1['CC'] = [111, 222, 333]
         df1
Out[10]:    CC
         0 111
         1 222
         2 333
In [11]: len(df1.columns)
Out[11]: 1

# Note the persisting series with rows containing `NaN` values in df2
In [12]: df2['CC'] = [111, 222, 333]
         df2
Out[12]:    AA  BB   CC
         0 NaN NaN  111
         1 NaN NaN  222
         2 NaN NaN  333
In [13]: len(df2.columns)
Out[13]: 3

 

It is evident that the original columns in df2 have re-surfaced. Therefore, it is prudent to instead read the length of the columns index with len(pandas.core.frame.DataFrame.columns) to see if a dataframe is empty.

원래 열이 df2에서 다시 나타났음을 알 수 있습니다. 따라서 데이터프레임이 비어 있는지 확인하기 위해 len(pandas.core.frame.DataFrame.columns)을 사용하여 컬럼 인덱스의 길이를 읽는 것이 현명합니다.

 

Practical solution

실용적 해결책
# New dataframe df
In [1]: df = pd.DataFrame({'AA' : [1, 2, 3], 'BB' : [11, 22, 33]})
        df
Out[1]:    AA  BB
        0   1  11
        1   2  22
        2   3  33

# This data manipulation approach results in an empty df
# because of a subset of values that are not available (`NaN`)
In [2]: df = df[df['AA'] == 5]
        df
Out[2]: Empty DataFrame
        Columns: [AA, BB]
        Index: []

# NOTE: the df is empty, BUT the columns are persistent
In [3]: len(df.columns)
Out[3]: 2

# And accordingly, the other answers on this page
In [4]: len(df.index)  # or len(df)
Out[4]: 0

In [5]: df.empty
Out[5]: True
# SOLUTION: conditionally check for empty columns
In [6]: if len(df.columns) != 0:  # <--- here
            # Do something, e.g. 
            # drop any columns containing rows with `NaN`
            # to make the df really empty
            df = df.dropna(how='all', axis=1)
        df
Out[6]: Empty DataFrame
        Columns: []
        Index: []

# Testing shows it is indeed empty now
In [7]: len(df.columns)
Out[7]: 0

 

Adding a new data series works as expected without the re-surfacing of empty columns (factually, without any series that were containing rows with only NaN):

새로운 데이터 시리즈를 추가하면, 행이 NaN만 포함한 행이 아예 없는 경우와 같이 예상대로 작동합니다:
In [8]: df['CC'] = [111, 222, 333]
         df
Out[8]:    CC
         0 111
         1 222
         2 333
In [9]: len(df.columns)
Out[9]: 1

 

 

출처 : https://stackoverflow.com/questions/19828822/how-to-check-whether-a-pandas-dataframe-is-empty

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