Python中使用for循环修改两个变量时报字符串索引必须为整数错误如何解决
错误原因
- 核心问题是你拼接得到的
'L1_'+str(acceleration[x])只是普通字符串,并非你代码中已定义的DataFrame变量,直接对字符串用列名字符串做索引,违反了Python字符串只能用整数/切片索引的规则,因此触发string indices must be integers报错。 - 次要问题是循环逻辑不合理:你遍历
range(len(acceleration))得到的是下标,后续取值需要额外再从acceleration元组中取值,多了不必要的嵌套;且初始化时固定写死了L1_25等变量,没有适配动态后缀的逻辑。
修正方案
快速适配版(直接复用你现有散列变量)
通过Python内置的globals()函数,通过动态变量名获取内存中实际的DataFrame对象即可:
import pandas as pd columns = ('node1', 'node2', 'node3', 'node4', 'node5', 'node6', 'node7', 'node8', 'node9') acceleration = (20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90) node = pd.DataFrame() # 先遍历加速度后缀,再遍历列名,逻辑更清晰避免重复拼接 for acc in acceleration: # 动态获取对应后缀的4个DataFrame L1 = globals()[f'L1_{acc}'] L2 = globals()[f'L2_{acc}'] L3 = globals()[f'L3_{acc}'] L4 = globals()[f'L4_{acc}'] for col in columns: node = pd.concat([node, L1[col], L2[col], L3[col], L4[col]], axis=1)
规范优化版(更易维护)
不建议将多个DataFrame作为散列变量存放,提前将所有DataFrame整理到嵌套字典中,避免使用globals()这种不严谨的写法:
import pandas as pd columns = ('node1', 'node2', 'node3', 'node4', 'node5', 'node6', 'node7', 'node8', 'node9') acceleration = (20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90) # 提前构建DataFrame映射字典,也可以在读取数据源时直接存入该字典 df_map = {} for acc in acceleration: df_map[acc] = { 'L1': globals()[f'L1_{acc}'], 'L2': globals()[f'L2_{acc}'], 'L3': globals()[f'L3_{acc}'], 'L4': globals()[f'L4_{acc}'] } # 拼接逻辑 node = pd.DataFrame() for acc in acceleration: curr = df_map[acc] for col in columns: node = pd.concat([node, curr['L1'][col], curr['L2'][col], curr['L3'][col], curr['L4'][col]], axis=1)
内容的提问来源于stack exchange,提问作者Kim Yejun
相关产品推荐
相关产品推荐

