python - Pandas astype int 不从值中删除小数点
问题描述
我尝试使用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
解决方案
问题在于.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
推荐阅读
- python - 从两个表sqlite python中迭代变量
- ios - 在 Firebase 中执行多字段关键字搜索
- r - R中的(稀疏)矩阵
- java - 错误的链表类型
- oracle - DBMS_LOB.LoadFromFile 健全性检查
- linux - 用于 git 拉取多个存储库的并行化脚本
- angular - Angular Material 颜色不会使用自定义主题更改
- android - 更改 Android Shashlik 模拟器输入语言
- go - Emacs编译忽略编译命令变量
- sql-server - 如何使用 sys.dm_os_sys_info 中的 cpu_ticks 数据获取 cpu 利用率