gpt4 book ai didi

python Pandas 错误: too many indices for array

转载 作者:太空宇宙 更新时间:2023-11-04 09:27:45 25 4
gpt4 key购买 nike

我有一个列数据框,我想将其转换为数字,如下所示:

for col in df.columns[22:33]:
df[col] = pd.to_numeric(df[col], errors = 'coerce')

效果很好。但是,每当我尝试包含多个范围时,如下所示:

for col in df.columns[22:66, 68, 69, 71, 72, 74:79, 81:86, 88, 89,91:94 ]:
df[col] = pd.to_numeric(df[col], errors = 'coerce')

我得到了错误,

IndexError:  too many indices for array

有没有办法解决这个问题,我不想对每个范围都一遍又一遍地这样做。谢谢。

最佳答案

这是 np.r_ 的功能。您传入数字和切片数组,它会将它们构造/连接到扩展数组中。

cols = np.r_[22:66, 68, 69, 71, 72, 74:79, 81:86, 88, 89,91:94]

array([22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 68, 69, 71, 72, 74, 75, 76,
77, 78, 81, 82, 83, 84, 85, 88, 89, 91, 92, 93])

在那之后,你可以使用 cols as

df.columns[cols]

关于 python Pandas 错误: too many indices for array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56909359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com