gpt4 book ai didi

python - 当存在 unicode 值时计算 NaN

转载 作者:太空狗 更新时间:2023-10-30 01:01:50 24 4
gpt4 key购买 nike

大家早上好

我有一个包含多个系列的 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()

最佳答案

使用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

但是请注意,pd.isnull 也将 None 视为 True:

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

关于python - 当存在 unicode 值时计算 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22043601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com