Python pandas 检查数据框是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36543606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:01:22  来源:igfitidea点击:

Python pandas check if dataframe is not empty

pythonpython-3.xpandas

提问by Arthur Zangiev

I have an ifstatement where it checks if the data frame is not empty. The way I do it is the following:

我有一个if语句,它检查数据框是否为空。我这样做的方式如下:

if dataframe.empty:
    pass
else:
    #do something

But really I need:

但我真的需要:

if dataframe is not empty:
    #do something

My question is - is there a method .not_empty()to achieve this? I also wanted to ask if the second version is better in terms of performance? Otherwise maybe it makes sense for me to leave it as it is i.e. the first version?

我的问题是 - 有没有办法.not_empty()实现这一目标?我也想问第二个版本在性能方面是否更好?否则也许我将它保留为第一个版本是有意义的?

回答by Akshat Mahajan

Just do

做就是了

if not dataframe.empty:
     # insert code here

The reason this works is because dataframe.emptyreturns Trueif dataframe is empty. To invert this, we can use the negation operator not, which flips Trueto Falseand vice-versa.

这样做的原因是因为如果数据框为空则dataframe.empty返回True。为了反转这个,我们可以使用否定运算符not,它可以翻转TrueFalse反之亦然。

回答by Santhosh

.empty returns a boolean value

.empty 返回一个布尔值

>>> df_empty.empty
True

So if not empty can be written as

所以如果不为空可以写成

if not df.empty:
    #Your code

Check pandas.DataFrame.empty, might help someone.

检查pandas.DataFrame.empty,可能会帮助某人。

回答by Rajarshi Das

You can use the attribute dataframe.emptyto check whether it's empty or not:

您可以使用该属性dataframe.empty来检查它是否为空:

if not dataframe.empty:
    #do something

Or

或者

if len(dataframe) != 0:
   #do something

Or

或者

if len(dataframe.index) != 0:
   #do something

回答by Arjun

Another way:

其它的办法:

if dataframe.empty == False:
    #do something`