>我有一个数据帧,其中可能的选项为真或假 由于存在 NaN 案例,熊猫将列作为浮动列,并在归因后 该列并获取值:0、0.5 和 1
如何添加约束以仅获得 0 和 1? 目前我正在使用丢失的库
from missingpy import MissForest
你介意用一些你使用的数据的例子和给你问题的代码来更新你的问题吗 - 它会让你得到更好的答案!
从你的说法来看,模型看起来是拟合的,是将你的目标变量视为连续的而不是分类的(布尔值本质上是分类 0 或 1(。MissForest上的API文档说:
第一步涉及填充剩余值的任何缺失值, 非候选列,具有初始猜测的列,即列均值 对于表示数值变量的列和表示数值变量的列模式 表示分类变量的列。请注意,分类 变量需要在估算器的 fit(( 期间显式标识 方法调用(有关更多信息,请参阅 API(。
这意味着您应该在拟合阶段指定cat_vars
:
fit(self, X, y=None, cat_vars=None(: 将推算器拟合在 X 上。
Parameters ---------- X : {array-like}, shape (n_samples, n_features) Input data, where ``n_samples`` is the number of samples and ``n_features`` is the number of features. cat_vars : int or array of ints, optional (default = None) An int or an array containing column indices of categorical variable(s)/feature(s) present in the dataset X. ``None`` if there are no categorical variables in the dataset. Returns ------- self : object Returns self.
参考此处。
这意味着将使用类别而不是连续值进行插补。
你有几个处理nan
的策略,让我们考虑一下这个玩具df
:
import pandas as pd
import numpy as np
df = pd.DataFrame(
{
'column': [np.nan, True, np.nan]
}
)
print(df['column'])
>>>
0 NaN
1 True
2 NaN
Name: column, dtype: object
如果您有能力处理损坏的数据(不可取(,则可以简单地将列强制为bool
类型:
print(df['column'].astype(bool))
>>>
0 True
1 True
2 True
Name: column, dtype: bool
您可以删除包含nan
的行(最佳方法(:
print(df['column'].dropna())
>>>
1 True
Name: column, dtype: object
或者,您可以将这些nan
替换为默认值:
print(df['column'].fillna(False))
>>>
0 False
1 True
2 False
Name: column, dtype: bool