【问题标题】:Impute binary values in python在python中输入二进制值
【发布时间】:2020-05-15 07:20:59
【问题描述】:

我有一个缺失值的数据框,其中可能的选项是 True 或 False 由于存在 NaN 情况,pandas 将该列作为浮点数,并且在估算之后 该列并获取值:0、0.5 和 1

如何添加约束以仅获取 0 和 1? 目前我正在使用missingpy库

from missingpy import MissForest

【问题讨论】:

  • 请为您的数据框显示一些代码和示例(输入和预期输出)。

标签: python imputation


【解决方案1】:

你有几个应对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

【讨论】:

    【解决方案2】:

    您介意用一些您使用的数据示例和给您问题的代码来更新您的问题吗 - 它会让您得到更好的答案!

    从您的说法看来,适合的模型正在考虑您的目标变量是连续的而不是分类的(布尔值本质上是分类的 0 或 1)。 MissForest 上的 API 文档说:

    第一步涉及填充剩余的任何缺失值, 非候选,具有初始猜测的列,即列均值 对于表示数值变量的列和列模式 代表分类变量的列。请注意,分类 在 imputer 的 fit() 期间需要明确识别变量 方法调用(有关详细信息,请参阅 API)。

    这意味着您应该在适合阶段指定cat_vars

    fit(self, X, y=None, cat_vars=None): 将 imputer 安装在 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.
    

    参考here

    这意味着将使用类别而不是连续值进行估算。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-17
      • 2021-06-13
      • 2015-07-02
      • 1970-01-01
      相关资源
      最近更新 更多