绘制数据集数值特征histogram直方图时代码运行报错该如何解决
问题原因
- 当子图只有1行时,
plt.subplots()返回的axes是一维数组,你使用的二维索引axes[this_row][this_col]会触发类型错误。当前3个数值特征、每行放3个的场景下,rows计算结果为1,此时axes长度为3,直接按索引取即可,不需要两层索引。 - 常用客户流失数据集中的
TotalCharges字段默认是字符串格式,包含空字符串或带空格的数值,无法直接绘制直方图,需要先转换为数值类型,处理异常值。
修复后的可运行代码
import numpy as np import pandas as pd import matplotlib.pyplot as plt # 先处理TotalCharges字段类型转换,非数值转为NaN df_train['TotalCharges'] = pd.to_numeric(df_train['TotalCharges'], errors='coerce') # 可根据需求选择填充空值或删除空值行,此处示例填充为0 df_train['TotalCharges'] = df_train['TotalCharges'].fillna(0) numeric_features = ['tenure', 'MonthlyCharges', 'TotalCharges'] cols = 3 rows = int(np.ceil(len(numeric_features)/cols)) fig, axes = plt.subplots(rows, cols, figsize=(16,6)) # 将axes统一转为二维数组,兼容1行/多行场景,避免索引错误 axes = np.atleast_2d(axes) for i in range(len(numeric_features)): this_row = int(np.floor(i/cols)) this_col = int(i%cols) feat = numeric_features[i] this_ax = axes[this_row][this_col] this_ax.hist(df_train[feat], bins=25) this_ax.set_title(feat) this_ax.grid() plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者henryD
相关产品推荐
相关产品推荐

