绘制y_train柱状图时遭遇AttributeError:'numpy.ndarray'对象无'value_counts'属性的解决求助
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

