如何遍历DataFrame的列并更新值?KeyError:32.5报错求助
报错根因
你代码中for i, j in zip(data.iloc[:, 0], data.iloc[:, 1])遍历得到的i、j是DataFrame第0列、第1列的单元格数值,后续你直接用data[i]、data[j]访问,是把数值当做列名去取列,你的DataFrame中不存在名为32.5的列,因此触发KeyError。
修复方案
按你的需求,是要对第0列、第1列的所有值做标准化计算,完全不需要遍历,直接使用pandas向量化整列运算即可,效率更高也不会出现索引错误:
# 第0列使用cost_T、int_T参数计算 df.iloc[:, 0] = (df.iloc[:, 0] - 455) / 31 # 第1列使用cost_F、int_F参数计算 df.iloc[:, 1] = (df.iloc[:, 1] - 501) / 42
如果你需要封装为函数可以写成:
def standardize_data(data, cost_T, int_T, cost_F, int_F): data.iloc[:, 0] = (data.iloc[:, 0] - cost_T) / int_T data.iloc[:, 1] = (data.iloc[:, 1] - cost_F) / int_F standardize_data(df, 455, 31, 501, 42)
如果你的场景确实需要逐行处理数据,可以按行索引遍历定位单元格:
def iterate_by_row(data, cost_T, int_T, cost_F, int_F): for row_idx in range(len(data)): # 定位到第row_idx行第0列的单元格修改值 data.iloc[row_idx, 0] = (data.iloc[row_idx, 0] - cost_T) / int_T # 定位到第row_idx行第1列的单元格修改值 data.iloc[row_idx, 1] = (data.iloc[row_idx, 1] - cost_F) / int_F iterate_by_row(df, 455, 31, 501, 42)
提示:非必要不推荐逐行遍历操作,pandas向量化运算的执行效率是逐行遍历的几十到上百倍。
内容的提问来源于stack exchange,提问作者user12441225
相关产品推荐
相关产品推荐

