【问题标题】:Pandas astype int not removing decimal points from valuesPandas astype int 不从值中删除小数点
【发布时间】:2021-01-10 21:03:04
【问题描述】:

我尝试使用 round 然后 astype 将浮点 DataFrame 的某些列中的值转换为整数。但是,这些值仍然包含小数位。我的代码有什么问题?

nums = np.arange(1, 11)
arr = np.array(nums)
arr = arr.reshape((2, 5))
df = pd.DataFrame(arr)
df += 0.1
df

原始df:

    0   1   2   3   4
0   1.1 2.1 3.1 4.1 5.1
1   6.1 7.1 8.1 9.1 10.1

然后四舍五入到 int 代码:

df.iloc[:, 2:] = df.iloc[:, 2:].round()
df.iloc[:, 2:] = df.iloc[:, 2:].astype(int)
df

输出:

    0   1   2   3   4
0   1.1 2.1 3.0 4.0 5.0
1   6.1 7.1 8.0 9.0 10.0

预期输出:

    0   1   2   3   4
0   1.1 2.1 3   4   5
1   6.1 7.1 8   9   10

【问题讨论】:

  • 熊猫似乎很谨慎。设置值时它不会向下转换列(因为 float 可以保持 int 保持浮动)但它会在必要时向上转换类型(即,如果您尝试将其设置为字符串值,则会更改为对象)

标签: python pandas


【解决方案1】:

解决这个问题的一种方法是使用.convert_dtypes()

df.iloc[:, 2:] = df.iloc[:, 2:].round()
df = df.convert_dtypes()
print(df)

输出:

     0    1  2  3   4
0  1.1  2.1  3  4   5
1  6.1  7.1  8  9  10

它将帮助您强制数据框的所有 dtype 更好地适应。

【讨论】:

    【解决方案2】:

    问题在于 .iloc 它分配了值并且没有更改列类型

    l = df.columns[2:]
    df[l] = df[l].astype(int)
    df
         0    1  2  3   4
    0  1.1  2.1  3  4   5
    1  6.1  7.1  8  9  10
    

    【讨论】:

      猜你喜欢
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多