Python中可用哪些循环或函数简化含iloc的重复计算代码?
简化重复遍历代码的实现方案
你不需要手动维护IndexPosition计数器做重复赋值,以下两种方式可以直接实现需求:
基础for循环实现(可读性优先)
你的IndexList本身存储的就是需要传入的行索引值,不需要额外调用.index()查找位置,直接遍历列表元素即可:
IndexList = list(range(100)) # 对应你写的0-99索引列表 results = [] for row_index in IndexList: current_result = dfColumn1.iloc[row_index] / dfFunction(row_index) results.append(current_result) # 按要求格式输出 print(f"#Output of function from Index Position {row_index + 1}") print(current_result)
列表推导式实现(简洁优先)
如果不需要逐行打印计算过程,可以用列表推导式一行完成所有结果的计算,后续再统一输出:
# 一次性计算所有索引对应的结果 results = [dfColumn1.iloc[idx] / dfFunction(idx) for idx in range(100)] # 统一按格式打印 for position, result in enumerate(results, start=1): print(f"#Output of function from Index Position {position}") print(result)
封装函数返回<function __main__.()>的原因
出现这个返回值是因为你封装逻辑时,返回的是函数对象本身,没有加括号传入参数执行函数。比如错误写法为return dfFunction,正确写法需要传入参数调用:return dfFunction(row_index)。
补充优化提示:如果你自定义的
dfFunction支持pandas Series类型的向量化运算,完全不需要写循环,直接做整列运算即可,运行效率远高于逐行遍历:results = dfColumn1 / dfFunction(dfColumn1.index)
内容的提问来源于stack exchange,提问作者elizac
相关产品推荐
相关产品推荐

