【发布时间】:2015-06-01 09:22:59
【问题描述】:
我开始使用 Python 和 Anaconda。我正在尝试创建一个线图,类似于使用 R 成功生成的线图。当我尝试使用下面的代码尝试读取 csv 文件时,我收到错误 ValueError: x and y must have same first dimension
import csv
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
def getColumn(filename, column):
results = csv.reader(open(filename), delimiter="\t")
return [result[column] for result in results if len(result) > column]
Season = getColumn("vs.csv",0)
VORP = getColumn("vs.csv",2)
fig = plt.figure()
plt.figure("VORP vs Season")
plt.xlabel("Season")
plt.ylabel("VORP")
plt.legend(["PlayerA","PlayerB"], loc=9,ncol=2)
plt.plot(Season, VORP)
plt.show()
CSV 文件仅包含以下条目:
Season Player VORP
'0405' PlayerA .7
'0506' PlayerA .14
[and so on]
'0405' PlayerB .23
'0506' PlayerB -.3
[and so on]
【问题讨论】:
-
在其中一行中它没有。
-
你确定分隔符是
\t吗?您显示的内容似乎由一些空格分隔。 -
你可以试试:
results = csv.reader(open(filename), delimiter=" ", skipinitialspace=True)但是你想如何从两个字符串列表(Season和VORP将是什么)到一个情节还不清楚。 -
当我在 Excel 中打开该 csv 文件时,它们位于单独的列中,这就是我设置
delimiter="\t"的原因。如果我尝试delimiter=" ",我会得到同样的错误
标签: python csv numpy matplotlib