为什么 pandas.apply() 在空元素上执行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34574499/
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
Why is pandas.apply() executing on null elements?
提问by Alex
Supposedly, the pandas.apply() function does not apply to null elements. However, this is not occuring in the following code. Why is this happening?
据说,pandas.apply() 函数不适用于 null 元素。但是,这不会发生在以下代码中。为什么会这样?
import pandas as pd
df = pd.Series([[1,2],[2,3,4,5],None])
df
0 [1, 2]
1 [2, 3, 4, 5]
2 None
dtype: object
df.apply(lambda x: len(x))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Alexander\Anaconda3\lib\site-packages\pandas\core\series.py", l
ine 2169, in apply
mapped = lib.map_infer(values, f, convert=convert_dtype)
File "pandas\src\inference.pyx", line 1059, in pandas.lib.map_infer (pandas\li
b.c:62578)
File "<stdin>", line 1, in <lambda>
TypeError: object of type 'NoneType' has no len()
采纳答案by kliron
None and nan are semantically equivalent. There is no point in replacing None with numpy.nan. apply
will still apply the function to NaN elements.
None 和 nan 在语义上是等价的。用 numpy.nan 替换 None 没有意义。 apply
仍会将该函数应用于 NaN 元素。
df[2] = numpy.nan
df.apply(lambda x: print(x))
Output: [1, 2]
[2, 3, 4, 5]
nan
You have to check for a missing value in your function you want to apply or use pandas.dropna
and apply the function to the result:
您必须检查要应用或使用的函数中是否存在缺失值pandas.dropna
并将该函数应用于结果:
df.dropna().apply(lambda x: print(x))
Alternatively, use pandas.notnull()
which returns a series of booleans:
或者,使用pandas.notnull()
which 返回一系列布尔值:
df[df.notnull()].apply(lambda x: print(x))
Please also read: http://pandas.pydata.org/pandas-docs/stable/missing_data.html
另请阅读:http: //pandas.pydata.org/pandas-docs/stable/missing_data.html
And specifically, this:
具体来说,这个:
Warning:
One has to be mindful that in python (and numpy), the nan's don't compare equal, but None's do. Note that Pandas/numpy uses the fact that np.nan != np.nan, and treats None like np.nan.
警告:
必须注意,在 python(和 numpy)中,nan 不相等,但 None 不相等。请注意,Pandas/numpy 使用 np.nan != np.nan 的事实,并将 None 视为 np.nan。