我想将 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()
Run Code Online (Sandbox Code Playgroud)
切割适用于没有 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]
Run Code Online (Sandbox Code Playgroud)
当我剪切包含 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]
Run Code Online (Sandbox Code Playgroud)
我怎样才能得到以下输出?
0 (2.0, 3.0]
1 (0.999, 2.0]
2 (0.999, 2.0]
3 NaN
4 (2.0, 3.0]
Run Code Online (Sandbox Code Playgroud)
这很奇怪。问题不pd.NaT在于,您的系列具有objectdtype 而不是常规数字系列,例如float, int。
一个快速的解决方法是pd.NaT用np.nanvia替换fillna。这从触发器系列转换object到float64D型,也可能会导致更好的性能。
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]]
Run Code Online (Sandbox Code Playgroud)
更通用的解决方案是事先显式转换为数字:
s = pd.to_numeric(s, errors='coerce')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4625 次 |
| 最近记录: |