【问题标题】:Converting yes/no to integer type 1/0 (not just replacing) in Pandas data frame在 Pandas 数据框中将是/否转换为整数类型 1/0(不仅仅是替换)
【发布时间】:2021-08-31 17:36:30
【问题描述】:

在这里查看了几篇文章后,每篇文章都解释了如何用 1/0 替换列中的是/否,但是这些数字的数据类型仍然是“对象”并且不是浮点数或整数(即使在我使用 astype( int)),所以我不能对它们做进一步的操作。我的代码如下。 有谁知道现在如何将数据类型从 object 转换为 float 或 int?

df['Inter Plan'].replace({'no': 0, 'yes': 1}).astype(int)

print(df['Inter Plan'].dtypes)

【问题讨论】:

    标签: python pandas dataframe integer


    【解决方案1】:

    在替换之前尝试转换为str

    df['Inter Plan'] = df['Inter Plan'].str.replace({'no': 0, 'yes': 1}).astype(int)
    

    【讨论】:

      【解决方案2】:

      astype 返回一个熊猫系列,它没有到位。使用:

      df["Inter Plan"] = df['Inter Plan'].replace({'no': 0, 'yes': 1}).astype(int)
      

      astype 有一个 copy 选项,可让您就地执行操作,但由于您也在使用 replace,我认为您无法完成所有操作在一行中,所以最好只使用上面的代码。此外,就地选项(将copy 设置为False)带有警告:

      设置 copy=False 时要非常小心,因为值的更改可能会传播到其他 pandas 对象。

      【讨论】:

        【解决方案3】:

        一种方法:

        df['Inter Plan'].replace({'no': 0, 'yes': 1}, inplace=True).astype('int', copy=False)
        

        【讨论】:

        • 我相信'NoneType' object has no attribute 'astype' 会出错,因为inplace on replace 意味着它将返回None,而不是熊猫系列。
        猜你喜欢
        • 2020-01-04
        • 2017-10-14
        • 2015-01-15
        • 2019-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多