运行matplotsoccer热图代码报numpy.ndarray无value_counts属性错误求助
问题原因
value_counts()是Pandas Series对象专属的频次统计方法,NumPy数组原生没有该方法。你遇到的报错并非你贴出的代码直接调用了该方法,而是matplotsoccer.count()函数的内部实现逻辑,默认会对传入的x、y坐标参数调用value_counts()做频次统计,你当前传入的x、y是NumPy数组类型,不符合该函数的输入类型要求,因此触发属性错误。
解决方案
你可以选择以下任意一种方案解决问题:
- 方案1:将输入的x、y转为Pandas Series类型后再传入,改动最小
完整可运行代码如下:import pandas as pd # 将numpy数组转为Pandas Series x_series = pd.Series(x) y_series = pd.Series(y) hm = matplotsoccer.count(x_series, y_series, n=25, m=25) # 构建25x25坐标热力图 hm = scipy.ndimage.gaussian_filter(hm,1) # 对热力图做高斯模糊 matplotsoccer.heatmap(hm,cmap='Blues', figsize=20, linecolor="black", cbar=True) # 绘制热力图 - 方案2:不依赖Pandas,手动实现坐标频次统计,替换
matplotsoccer.count()逻辑
完整可运行代码如下:import numpy as np # 手动统计25x25网格内的坐标出现频次 x_bins = np.linspace(x.min(), x.max(), 25 + 1) y_bins = np.linspace(y.min(), y.max(), 25 + 1) hm, _, _ = np.histogram2d(x, y, bins=[x_bins, y_bins]) # 转置保证坐标维度和matplotsoccer.count输出结果对齐 hm = hm.T # 后续逻辑不变 hm = scipy.ndimage.gaussian_filter(hm,1) matplotsoccer.heatmap(hm,cmap='Blues', figsize=20, linecolor="black", cbar=True)
内容的提问来源于stack exchange,提问作者O.N.J.R P
相关产品推荐
相关产品推荐

