Ris*_*hik 9 python types casting dataframe pandas
在包含大约 40 多列的数据框中,我尝试使用 iloc 将前 27 列的 dtype 从 float 更改为 int:
df1.iloc[:,0:27]=df1.iloc[:,0:27].astype('int')
Run Code Online (Sandbox Code Playgroud)
但是,它不起作用。我没有收到任何错误,但 dtype 也没有改变。它仍然保持浮动。
现在最奇怪的部分:
如果我首先仅更改第一列的 dtype(如下所示):
df1.iloc[:,0]=df1.iloc[:,0].astype('int')
Run Code Online (Sandbox Code Playgroud)
然后运行前面的代码行:
df1.iloc[:,0:27]=df1.iloc[:,0:27].astype('int')
Run Code Online (Sandbox Code Playgroud)
它按要求工作。任何帮助理解这一点和解决方案的帮助将不胜感激。
谢谢!
我猜这是1.0.5. 我在我的1.0.5. 我和你有同样的问题。该.loc也有同样的问题,所以我想熊猫开发者在碰坏iloc/loc。您需要更新到最新的熊猫或使用解决方法。如果您需要解决方法,请按如下方式使用分配
df1[df1.columns[0:27]] = df1.iloc[:, 0:27].astype('int')
Run Code Online (Sandbox Code Playgroud)
我测试了它。以上方法克服了这个错误。它将前 27 列变成 dtypeint32