[英]pandas cut a series with nan values
我想將pandas cut功能應用於包含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()
對於沒有NaN的系列,切割效果很好:
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
dtype而不是常規數字序列,例如float
, int
。
一個快速的解決辦法是更換pd.NaT
與np.nan
通過fillna
。 這將觸發從object
到float64
dtype的系列轉換,也可能導致更好的性能。
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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.