如何在循环中使用字典值选取DataFrame列并解决dict_values不可下标报错
报错原因
Python 3 中dict.values()返回的是字典值的视图对象,不属于序列类型,不支持[下标]的方式直接取值,因此触发了TypeError。
另外你当前的逻辑还有隐藏问题:字典只有3组值,但是你x+y的计算结果最大为14,就算把dict_values转成列表,索引超过2也会触发索引越界报错。
是否需要改用嵌套列表
如果不需要用到字典的键作为分组标识,改用嵌套列表是更简洁的选择,不需要额外做类型转换,读写效率更高;如果需要保留分组名做后续处理(比如子图标题、分组标记),继续使用字典也没问题,只要把值提前转成列表即可。
修复&优化方案
快速修复现有代码
仅解决当前报错,只需要把dict_values转成列表即可,同时用取余运算避免索引越界:
把绘图行的some_dict.values()[x+y]修改为list(some_dict.values())[(x+y) % len(some_dict)]
更优实现逻辑
不用嵌套循环计算x+y,直接把⼦图数组扁平化遍历,逻辑更清晰,也不会出现索引错误:
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = pd.DataFrame({'price': [50, 35, 45, 93, 45], 'cost': [10, 11, 12, 13, 15], 'inventory': [100, 200, 300, 400, 500], 'popularity': [7, 4, 9, 4, 2], 'supply': [20, 30 , 40, 54, 69], 'demand': [30, 43, 56, 76, 98]}) # 不需要分组名直接用嵌套列表 plot_groups = [ ['cost', 'price'], ['inventory', 'popularity', 'supply'], ['supply', 'inventory', 'demand'] ] fig, axes = plt.subplots(8, 8, figsize = (55, 25)) axes_flat = axes.flatten() # 把二维子图数组转为一维,方便遍历 for idx, ax in enumerate(axes_flat): # 取余循环使用分组,避免索引越界 current_group = plot_groups[idx % len(plot_groups)] sns.heatmap(df[current_group].corr(), cmap = 'BuPu', annot = True, fmt = '0.2f', cbar= False, ax = ax ) plt.tight_layout() # 自动调整子图间距,避免标签重叠 plt.show()
如果需要保留字典的键作为分组名,调整为如下写法即可:
some_dict = {'first': ['cost', 'price'], 'second' : ['inventory', 'popularity', 'supply'], 'third': ['supply', 'inventory', 'demand']} dict_items = list(some_dict.items()) fig, axes = plt.subplots(8, 8, figsize = (55, 25)) axes_flat = axes.flatten() for idx, ax in enumerate(axes_flat): group_name, current_group = dict_items[idx % len(dict_items)] ax.set_title(group_name, fontsize=12) # 用字典键作为子图标题 sns.heatmap(df[current_group].corr(), cmap = 'BuPu', annot = True, fmt = '0.2f', cbar= False, ax = ax ) plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者b2bt
相关产品推荐
相关产品推荐

