Python 如何检查熊猫系列是否为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24652417/
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
How to check if pandas Series is empty?
提问by BP_
How to check if pandas Series is empty?
如何检查熊猫系列是否为空?
I have tried this:
我试过这个:
How to check whether a pandas DataFrame is empty?
but it seems that Series has no property 'isempty'.
但似乎 Series 没有属性“isempty”。
回答by DSF
According to the Pandas documentationyou need to use the empty
property and not isempty
根据 Pandas文档,您需要使用该empty
属性而不是isempty
E.g.
例如
In [12]: df.empty
Out[13]: False
回答by Zero
I use len function. It's much faster than empty(). len(df.index) is even faster.
我使用 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
'''
回答by sparrow
I use this to check if a particular column in a dataFrame has no values or is empty:
我用它来检查数据帧中的特定列是否没有值或为空:
len(df.col_name.value_counts()) > 0
回答by parik
If NDFrame contains onlyNaNs, it is still not considered empty. See the example below.
如果 NDFrame只包含NaN,它仍然不被认为是空的。请参阅下面的示例。
Examples
例子
An example of an actual empty DataFrame. Notice the index is empty:
实际空 DataFrame 的示例。注意索引为空:
>>> df_empty = pd.DataFrame({'A' : []})
>>> df_empty
Empty DataFrame
Columns: [A]
Index: []
>>> df_empty.empty
True
If we only have NaNsin our DataFrame, it is not considered empty! We will need to drop the NaNsto make the DataFrame empty:
如果我们的 DataFrame 中只有NaN,它不会被认为是空的!我们需要删除NaN以使 DataFrame 为空:
>>> df = pd.DataFrame({'A' : [np.nan]})
>>> df
A
0 NaN
>>> df.empty
False
>>> df.dropna().empty
True
回答by M T
Thanks @sparrow I used this to test for datetime columns:
谢谢@sparrow 我用它来测试日期时间列:
if len(df.select_dtypes(include='datetime').iloc[0].value_counts()) == 0:
print('DF DATETIME COLUMNS: ', len(df_dt.iloc[0].value_counts()))
None of the other methodes (a.any(), a.empty()...) worked. select returns with a non-empty index but with empty columns so I think that's it. I think it actually returns a series, hence the zero iloc.
其他方法(a.any()、a.empty()...)都不起作用。select 返回一个非空索引但带有空列,所以我认为就是这样。我认为它实际上返回了一个系列,因此 iloc 为零。