当unicode值存在时计算NaNs

Myl*_*ker 5 python numpy nan pandas python-unicode

大家早上好,

我有一个pandas包含多个系列的数据框.对于数据框中的给定系列,数据类型为unicode,NaN和int/float.我想确定系列中的NaN数量但不能使用内置numpy.isnan方法,因为它无法安全地将unicode数据转换为它可以解释的格式.我提出了一个解决方案,但我想知道是否有更好/更多的Pythonic方法来完成这项任务.

提前谢谢,迈尔斯

import pandas as pd
import numpy as np

test = pd.Series(data = [NaN, 2, u'string'])
np.isnan(test).sum()
#Error

#Work around
test2 = [x for x in test if not(isinstance(x, unicode))]
numNaNs = np.isnan(test2).sum()
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 6

使用pandas.isnull:

In [24]: test = pd.Series(data = [NaN, 2, u'string'])

In [25]: pd.isnull(test)
Out[25]: 
0     True
1    False
2    False
dtype: bool
Run Code Online (Sandbox Code Playgroud)

但请注意,这pd.isnullNone视为True:

In [28]: pd.isnull([NaN, 2, u'string', None])
Out[28]: array([ True, False, False,  True], dtype=bool)
Run Code Online (Sandbox Code Playgroud)