You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

绘制y_train柱状图时遭遇AttributeError:'numpy.ndarray'对象无'value_counts'属性的解决求助

Fixing AttributeError When Plotting y_train Distribution

Hey there! Let's get that bar plot working for you—you've been stuck on this long enough.

What's Causing the Error?

The AttributeError: 'numpy.ndarray' object has no attribute 'value_counts' pops up because your y_train is a numpy array, and value_counts() is a method exclusive to pandas Series/DataFrames. Looking at your code, y = reviews['Score'].values converts the pandas Series to a numpy array, so the split result y_train inherits that type.


Solution 1: Convert to Pandas Series (Quick & Familiar)

Just turn y_train into a pandas Series, and you can use value_counts() like you originally wanted. I also fixed your axis labels—they were swapped, which would have made the chart confusing:

import matplotlib.pyplot as plt
import pandas as pd

# Convert numpy array to pandas Series
y_train_series = pd.Series(y_train)
counts = y_train_series.value_counts()

# Plot the corrected bar chart
plt.bar(counts.index, counts.values, color='green')
plt.xlabel("y_train values")
plt.ylabel("Count")
plt.title("Distribution of y_train")
plt.show()

Solution 2: Use Numpy Directly (No Pandas Dependency)

If you prefer sticking with numpy, use np.unique() to get both the unique values and their counts:

import matplotlib.pyplot as plt
import numpy as np

# Extract unique values and their frequencies from the numpy array
values, counts = np.unique(y_train, return_counts=True)

# Plot the bar chart
plt.bar(values, counts, color='green')
plt.xlabel("y_train values")
plt.ylabel("Count")
plt.title("Distribution of y_train")
plt.show()

Either approach will generate the distribution plot you need, and both fix the original label mix-up so your chart makes intuitive sense.

内容的提问来源于stack exchange,提问作者mahesh mj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 00:47:43