python - Pandas astype int 不从值中删除小数点

标签 python pandas

我尝试使用 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 - Pandas astype int 不从值中删除小数点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64048662/

相关文章:

python - 如何在Python中求解带有矩阵变量的方程?

python - 如何在 Ubuntu 中删除 Python2?

python - 如何根据字符拆分列并在每次拆分时附加其余列

python - dataframe和csv文件的日期格式可以相同吗?

python - 使用 for 循环执行乘法变量的方法

python - 将 Abaqus 宏转换为 Python 脚本

python - PySpark 上 Spark-cassandra 的服务器端过滤

python-2.7 - 从 Pandas 的另一列中填充一列的缺失值

python - Pandas:用两列之一的值替换 Nan

python - “Unknown String Format” - 解析 pandas dataframe 中的 URL 时出错