Python中无法将CSV数据存入数组并绘制散点图问题求助
Fixing Your CSV-to-Array & Scatter Plot Issues in Python
Let's work through your two problems one by one—these are common beginner pitfalls, so we'll get your code up and running quickly!
1. Problem: Can't Store CSV Data in an Array
Looking at your original code, there are three critical issues blocking you here:
- You never initialize the
xlist/array or the indexibefore trying to use them—this will throw aNameErrorimmediately. - Values pulled from CSV files are strings by default, but you'll need numeric values (int/float) for plotting later.
- You're opening the same CSV file twice, which is unnecessary and inefficient. We can load both columns in a single pass.
Here's a cleaned-up way to load your data into lists (easier to work with than array.array for most use cases):
import csv # Initialize empty lists to store our data x_values = [] y_values = [] with open('Infosys.csv', 'r') as csv_file: csv_reader = csv.reader(csv_file) next(csv_reader) # Skip the header row for line in csv_reader: # Convert string values to numeric types (use int if your data is whole numbers) x_val = float(line[2]) y_val = float(line[5]) x_values.append(x_val) y_values.append(y_val) # If you specifically need array.array instead of lists: # from array import array # x_array = array('f', x_values) # y_array = array('f', y_values)
2. Problem: Can't Plot Scatter Graph from Array Data
Your scatter plot code fails for two main reasons:
- In your original code,
ygets overwritten with a single value every loop—you never collect all y-values into an array/list to matchx. - You didn't import
matplotlib.pyplot(required to create plots), and you forgot to callplt.show()to display the final graph.
Using the corrected data loading code above, here's how to make the scatter plot work:
import matplotlib.pyplot as plt # Use the lists we populated earlier plt.scatter(x_values, y_values, label='Data Points', color='red') plt.xlabel('Column 2 Values') # Add descriptive labels plt.ylabel('Column 5 Values') plt.title('Infosys Data Scatter Plot') plt.legend() plt.show() # This line renders the plot on your screen
Full Working Code
Putting everything together, here's the complete, tested script:
import csv import matplotlib.pyplot as plt x_values = [] y_values = [] with open('Infosys.csv', 'r') as csv_file: csv_reader = csv.reader(csv_file) next(csv_reader) for line in csv_reader: # Add a check to skip rows with missing values (prevents conversion errors) if line[2] and line[5]: x_values.append(float(line[2])) y_values.append(float(line[5])) plt.scatter(x_values, y_values, label='pt.', color='red') plt.xlabel('X Axis') plt.ylabel('Y Axis') plt.legend() plt.show()
Quick Extra Tips
- If your CSV has missing or malformed values, the
if line[2] and line[5]check will skip those rows to avoid crashes. - For larger datasets, using
pandascan simplify this even more (e.g.,df = pd.read_csv('Infosys.csv')thenplt.scatter(df.iloc[:,2], df.iloc[:,5])), but the above code uses only Python's standard libraries.
内容的提问来源于stack exchange,提问作者DARSHAN TERAIYA
相关产品推荐
相关产品推荐

