首页 > 解决方案 > 多列 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 的方法?

标签: pandas

解决方案


问题是一些无效值,如-/所以首先将它们转换为缺失值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

推荐阅读