python错误:数组的索引太多

python错误:数组的索引太多,python,pandas,dataframe,for-loop,Python,Pandas,Dataframe,For Loop,我有一个列的dataframe,我想将其转换为数字,如下所示: 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')

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

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')
这很有效。但是,每当我尝试包含多个范围时,例如:

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

有没有一种方法可以解决这个问题,我不想在每个范围内都反复这么做。谢谢。

您必须创建两个循环。创建一个包含范围元素的列表,然后在其上循环,在此循环中插入原始for循环代码

比如:


您的
范围列表将具有您需要的范围

假设您的目标列表示数据帧中列的整数名称(根据您的示例),您可以使用munge字符串并连接结果

target_cols_str = "22:66, 68, 69, 71, 72, 74:79, 81:86, 88, 89, 91:94"
df_series = []
for col in target_cols_str.split(','):
    col = col.strip()  # Remove any whitespace.
    if ':' in col:
        lhs, rhs = col.split(':')
        df_series.append(df.loc[:, int(lhs):int(rhs)])
    else:
        df_series.append(df.loc[:, int(col)])
df2 = pd.concat(df_series, axis=1)
应用于示例以将原始数据帧转换为数值:

target_cols_str = "22:66, 68, 69, 71, 72, 74:79, 81:86, 88, 89, 91:94"
for col in target_cols_str.split(','):
    col = col.strip()  # Remove any whitespace.
    if ':' in col:
    lhs, rhs = col.split(':')
    for col_name in range(int(lhs), int(rhs) + 1):
        df.loc[:, col_name] = pd.to_numeric(df.loc[:, col_name], errors = 'coerce')
    else:
        df.loc[:, int(col)] = pd.to_numeric(df.loc[:, int(col)], errors = 'coerce')

这是
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
作为

df.columns[cols]

我不太明白。整数是列索引。这是否允许我也转换列?谢谢。如果数字代表列的整数位置,只需将上面的所有
loc
值转换为
iloc
。在第二个示例中,我刚刚演示了列的转换Series@AndyL. 修改了解决方案来解释这一点。这太完美了!简单,正是我想要的谢谢@jvalenti:很高兴我能帮你注意到这种行为略有不同,例如,
22:66
导致第22-65列,而使用
df.loc[:,22:66]
则是第22-66列。理论上这是可行的。我遇到的问题是,我无法找到一种方法来指定语法一致的范围。我试过列表和元组,但都不起作用。我知道这有问题,但我仍然认为这是可行的。基本上,范围必须是整数的元组来存储int值,比如
range\u list=[(22,66)…]
等等,然后在第二次迭代中,通过
df.columns[tuple first element:tuple second element]
显式调用每个值。或者,您可能指的是单个范围输入,如
68,69,71
?如果是这样的话,就为它们创建一个范围。因此,代码将保持不变。