熊猫剪了一个带有nan值的系列



我想将pandas剪切函数应用于包含NaN的系列。所需的行为是,它对非NaN元素进行桶处理,并为NaN元素返回NaN。

import pandas as pd
numbers_with_nan = pd.Series([3,1,2,pd.NaT,3])
numbers_without_nan = numbers_with_nan.dropna()

对于没有NaNs:的系列,切割效果良好

pd.cut(numbers_without_nan, bins=[1,2,3], include_lowest=True)
0      (2.0, 3.0]
1    (0.999, 2.0]
2    (0.999, 2.0]
4      (2.0, 3.0]

当我剪切包含NaN的序列时,元素3被正确地返回为NaN,但最后一个元素被分配了错误的bin:

pd.cut(numbers_with_nan, bins=[1,2,3], include_lowest=True)
0      (2.0, 3.0]
1    (0.999, 2.0]
2    (0.999, 2.0]
3             NaN
4    (0.999, 2.0]

如何获得以下输出?

0      (2.0, 3.0]
1    (0.999, 2.0]
2    (0.999, 2.0]
3             NaN
4      (2.0, 3.0]

这很奇怪。问题不在于pd.NaT,而是您的序列具有object数据类型,而不是常规数字序列,例如floatint

快速解决方案是通过fillnapd.NaT替换为np.nan。这触发了从objectfloat64数据类型的串行转换,也可能带来更好的性能。

s = pd.Series([3, 1, 2, pd.NaT, 3])
res = pd.cut(s.fillna(np.nan), bins=[1, 2, 3], include_lowest=True)
print(res)
0    (2, 3]
1    [1, 2]
2    [1, 2]
3       NaN
4    (2, 3]
dtype: category
Categories (2, object): [[1, 2] < (2, 3]]

一个更通用的解决方案是事先显式地转换为数字:

s = pd.to_numeric(s, errors='coerce')

最新更新