如何检查熊猫Q4312079q是否为空?就我而言,如果DataFrame为空,我想在终端中打印一些消息。

评论

len()不起作用?对于空数据框,它应该返回0。

#1 楼

您可以使用属性df.empty来检查其是否为空:

if df.empty:
    print('DataFrame is empty!')


来源:Pandas Documentation

评论


这似乎很可耻,因为您需要知道df是pd.DataFrame。我想知道不在pd.DataFrame上实现bool()的动机。

–定量
2014年2月14日下午16:55

@Quant-文档讨论了bool为什么在此处引发数据框错误:链接。 Quote:“是不是因为它不是零长度而为True?是因为有False值是False?目前还不清楚,所以熊猫会引发ValueError”

–北京
14年4月18日在14:04

更快的方法是df.shape [0] == 0以检查数据帧是否为空。你可以测试一下。

–训练有素的bad
20 Nov 10 '13:40

#2 楼

我使用len函数。它比empty快得多。 len(df.index)甚至更快。

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(10000, 4), columns=list('ABCD'))

def empty(df):
    return df.empty

def lenz(df):
    return len(df) == 0

def lenzi(df):
    return len(df.index) == 0

'''
%timeit empty(df)
%timeit lenz(df)
%timeit lenzi(df)

10000 loops, best of 3: 13.9 µs per loop
100000 loops, best of 3: 2.34 µs per loop
1000000 loops, best of 3: 695 ns per loop

len on index seems to be faster
'''


评论


由于len(df.index)== 0或len(df.columns)== 0,因此DataFrame可以为空。

–马克·霍瓦斯(Mark Horvath)
16年11月4日在9:53

#3 楼

我更喜欢长途旅行。这些是我为避免使用try-except子句而执行的检查-


检查变量是否不为None
,然后检查其是否为数据框,并确保
它不是空的

这里,DATA是可疑变量-

DATA is not None and isinstance(DATA, pd.DataFrame) and not DATA.empty


评论


如果期望变量是空的或具有行的DataFrame(这就是OP的含义),那么这是多余的,也是一种坏习惯。如果不是DF(或者不是DF),则应抛出异常,因为某个地方出了问题。

– fgblomqvist
19-09-19在22:06

在Python中,try / except很便宜,如果很贵。 Python既不是Java也不是C。在这里,宽恕要比许可容易

–尼克·玛丽娜(Nick Marina)
20-4-14的1:26

#4 楼

要查看一个数据框是否为空,我认为应该测试一个数据框的列索引的长度:
 if len(df.columns) == 0: 1
 

原因:
根据Pandas Reference API,存在以下区别:

具有0行和0列的空数据框

具有包含NaN的行的空数据框因此至少有1列


可以说,它们是不一样的。其他答案是不精确的,因为df.emptylen(df)len(df.index)不区分大小写,并且返回索引均为0,并且在这两种情况下返回的都是true。
 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
 

示例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
 

。在读取第一个加载的数据帧df1的列索引长度时,它返回0列以证明它确实为空。
 In [8]: len(df1.columns)
Out[8]: 0

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

关键地,虽然第二个数据帧df2不包含任何数据,但它并不是完全为空,因为它返回了持久存在的空列的数量。
为什么重要
让我们向这些数据帧中添加一个新列了解其含义:
 # 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
 

很明显,df2中的原始列已经重新出现。因此,建议改用len(pandas.core.frame.DataFrame.columns)读取列索引的长度,以查看数据帧是否为空。 pre>
 # 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 的行的系列): / pre>

#5 楼

1) If a DataFrame has got Nan and Non Null values and you want to find whether the DataFrame
is empty or not then try this code.
2) when this situation can happen? 
This situation happens when a single function is used to plot more than one DataFrame 
which are passed as parameter.In such a situation the function try to plot the data even 
when a DataFrame is empty and thus plot an empty figure!.
It will make sense if simply display 'DataFrame has no data' message.
3) why? 
if a DataFrame is empty(i.e. contain no data at all.Mind you DataFrame with Nan values 
is considered non empty) then it is desirable not to plot but put out a message :
Suppose we have two DataFrames df1 and df2.
The function myfunc takes any DataFrame(df1 and df2 in this case) and print a message 
if a DataFrame is empty(instead of plotting):


df1                     df2
col1 col2           col1 col2 
Nan   2              Nan  Nan 
2     Nan            Nan  Nan  


和功能:

def myfunc(df):
  if (df.count().sum())>0: ##count the total number of non Nan values.Equal to 0 if DataFrame is empty
     print('not empty')
     df.plot(kind='barh')
  else:
     display a message instead of plotting if it is empty
     print('empty')


评论


虽然这段代码可以解决问题,但包括解释如何以及为什么解决该问题的说明,确实可以帮助提高您的帖子质量,并可能导致更多的投票。请记住,您将来会为读者回答问题,而不仅仅是现在问的人。请编辑您的答案以添加说明,并指出适用的限制和假设。来自评论

–双响
20-05-28在15:45