【问题标题】:Python - reading from CSV - ValueError: x and y must have same first dimensionPython - 从 CSV 读取 - ValueError:x 和 y 必须具有相同的第一维
【发布时间】: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) 但是你想如何从两个字符串列表(SeasonVORP 将是什么)到一个情节还不清楚。
  • 当我在 Excel 中打开该 csv 文件时,它们位于单独的列中,这就是我设置 delimiter="\t" 的原因。如果我尝试delimiter=" ",我会得到同样的错误

标签: python csv numpy matplotlib


【解决方案1】:

一种解决方案是使用 Anaconda 附带的pandas 数据分析库。它应该提供一些与 R 相同的功能,所以它对你来说可能是一个不错的选择。它极大地简化了从 csv 文件导入和操作数据。它还具有很好的plotting 功能,使用matplotlib

首先,导入pandasmatplotlib.pyplot,并使用前者从您的csv 创建一个pandas.DataFrame 对象。如果您将 DataFrame 打印到控制台,您会看到它看起来非常漂亮。

>>> import pandas as pd
>>> import matplotlib.pyplot as plt
>>>
>>> df = pd.DataFrame.from_csv('vorp.csv', index_col=None)
>>> print df

   Season   Player  VORP
0  '0405'  PlayerA  0.70
1  '0506'  PlayerA  0.14
2  '0405'  PlayerB  0.23
3  '0506'  PlayerB -0.30

现在在您的 DataFrame 上调用 pivot_table 方法。这只会返回另一个 DataFrame 对象,但它将以一种易于绘制的方式组织。您需要将“VORP”设置为值,将“Season”设置为索引(即行),将“Player”设置为列,如下所示:

>>> table = df.pivot_table('VORP', 'Season', 'Player')
>>> print table

Player  PlayerA  PlayerB
Season                  
'0405'     0.70     0.23
'0506'     0.14    -0.30

现在只需绘制表格即可。只需在数据透视表上调用plot 方法(这将返回一个matplotlib.axes 对象),然后使用matplotlib 随意操作它。例如,我添加了 y 轴标签和标题。

>>> ax = table.plot()
>>> ax.set_title('VORP vs Season')
>>> ax.set_ylabel('VORP')
>>> plt.show()

这是结果,毫无疑问,使用完整的数据集看起来会更好。

【讨论】:

  • 非常感谢,这更有意义
猜你喜欢
  • 1970-01-01
  • 2016-11-10
  • 2017-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 2018-02-15
相关资源
最近更新 更多