pandas - 多列 int
问题描述
我正在使用以下数据:
将熊猫导入为 pd
url="https://raw.githubusercontent.com/dothemathonthatone/maps/master/population.csv"
bevdf2=pd.read_csv(url)
我想将多个文件从对象更改为整数。我最近发现 .loc
并想使用它:
aus = bevdf2.iloc[:, 39:75]
bevdf2[aus] = bevdf2[aus].astype(int)
但我得到这个输出:
Boolean array expected for the condition, not object
是否有一个简单的继续使用 .loc 工具将多列转换为 int 的方法?
解决方案
问题是一些无效值,如-
,/
所以首先将它们转换为缺失值to_numeric
,如果需要将浮点数转换为整数,请使用Int64
(熊猫 0.24+):
bevdf2.iloc[:, 39:75] = (bevdf2.iloc[:, 39:75]
.apply(pd.to_numeric, errors='coerce')
.astype('Int64'))
print (bevdf2.iloc[:, 39:75].dtypes)
deu50 Int64
aus15 Int64
aus16 Int64
aus17 Int64
aus18 Int64
aus19 Int64
aus20 Int64
aus21 Int64
aus22 Int64
aus23 Int64
aus24 Int64
aus25 Int64
aus26 Int64
aus27 Int64
aus28 Int64
aus29 Int64
aus30 Int64
aus31 Int64
aus32 Int64
aus33 Int64
aus34 Int64
aus35 Int64
aus36 Int64
aus37 Int64
aus38 Int64
aus39 Int64
aus40 Int64
aus41 Int64
aus42 Int64
aus43 Int64
aus44 Int64
aus45 Int64
aus46 Int64
aus47 Int64
aus48 Int64
aus49 Int64
dtype: object
推荐阅读
- angular - 尝试将属性用于 [(value)] 时出错
- android - Android Biometrics - 选择哪种方法(回退到密码)?
- c++ - C++意外调用继承类的函数
- python - run_algorithm() 失败,因为它无法从 Internet 源获取数据(403 Forbidden)
- tinymce - 所见即所得编辑器不会在 Chrome 中激活
- r - 如何使用 ggplot2 用多边形列表绘制我的形状?
- javascript - 如何检查数组中的对象是否有空字符串?
- c - 如何修复由-Wconversion引起的错误?
- html - 如何修改我的 css 或 cshtml 以获得类似于 w3school 上的下拉导航栏?
- python - Python代码在程序/代码的开头跳回?