使用Python3将csv列打印为列表,然后使用Matplotlib生成图形
我正在尝试使用matplotlib从csv文件中的列生成图形。到目前为止,我已经:使用Python3将csv列打印为列表,然后使用Matplotlib生成图形,python,python-3.x,graphing,Python,Python 3.x,Graphing,我正在尝试使用matplotlib从csv文件中的列生成图形。到目前为止,我已经: X = [] Y = [] for line in file: column=line.split(',') year=str(column[3]) for year in X: X.append(year) for line in file: column=line.split(',') emissions=str(column[4]) for e
X = []
Y = []
for line in file:
column=line.split(',')
year=str(column[3])
for year in X:
X.append(year)
for line in file:
column=line.split(',')
emissions=str(column[4])
for emissions in Y:
Y.append(emissions)
plt.plot(X,Y)
但是它打印出的是一个空白的绘图。只需使用熊猫即可
import pandas as pd
import matplotlib.pyplot as plt
# Read CSV
df = pd.read_csv('yourcsv.csv')
X = df.iloc[:, 0] # First column
Y = df.iloc[:, 1] # Second column
print('First column: ', list(X), 'Second column: ', list(Y))
plt.plot(X, Y)
请记住,一个文件只能读取一次。在第一个循环之后,您就到了文件的末尾。当你需要整数时,为什么要转换成字符串呢?您所需要的就是:
X = []
Y = []
for line in file:
column=line.split(',')
X.append(int(column[3]))
Y.append(int(column[4]))
plt.plot(X,Y)
请使用标记功能键入代码。至于你的代码,你有“X年”。X中没有任何东西,X中也永远不会有任何东西。和“Y中的排放”一样。你想在X和Y里放什么?你可能想要
X.append(int(column[3])和Y.append(int(column[4]))
?蒂姆·罗伯茨说的是正确的。X开始时为空,因此X中的年为空for循环