【问题标题】:Q: is there a way to ignore blanks cells in a csv file but still graph the data问:有没有一种方法可以忽略 csv 文件中的空白单元格,但仍将数据绘制成图表
【发布时间】:2019-03-29 16:41:26
【问题描述】:

我正在使用 Python 为学校做一个个人项目。我只是想使用 matplotlib.pyplot 和 pandas 清理和绘制 csv 文件中的数据。我遇到的一个问题是 csv 中的空白单元格将其读取为 0。

我以前解决此问题的尝试是删除 csv 中的所有空白单元格,但这(显然)给了我一个错误,因为 y 轴上的点数与 x 轴上的点数不同-轴。

数据:

unix 时间

,1296086400,1297900800,1299542400,132753600,1330992000,1358985600,1360627200,1362441600,1390435200,1392076800,1393891200

贝克尔,18:20.6,17:53.1,18:06.2,18:00.3,17:51.2,18:05.0,18:05.3,18:14.9,,, 凯西,19:14.7,17:51.2,17:16.4,17:18.6,16:49.3,17:05.0,17:02.7,16:51.2,16:57.0,16:57.4,16:44.2 周五,17:18.9,17:00.9,16:54.1,16:47.5,16:34.1,16:33.0,16:23.3,16:22.5,16:27.0,16:10.1,16:15.6 羊肉,18:09.6,17:50.7,17:39.9,,17:42.9,17:44.0,17:35.2,,,, 贵族,18:18.9,17:42.0,17:31.2,17:26.9,17:14.0,17:43.0,17:59.2,17:19.9,17:25.0,17:42.7, 沃里斯,,18:49.2,18:19.4,17:29.8,16:53.9,17:07.0,16:50.6,16:44.6,16:50.0,16:47.3,16:41.2

'''
first try at dealing with blank cells in the csv file 
doesnt work because the graph needs to have the same amount 
of plot points in the x as it does in the y. 
'''
with open('clean3.csv') as f:
    reader = csv.reader(f)
    header = next(reader)
    dates = cleanLine(header)
    user_list = []  # new list for inputs
    for row in reader:
        scores = []
        for i in range(len(row)):
            if (row[i] != '' ):
                try:
                    errorCheck = float(row[i][:2])  
       # checks if the value of row[i] can be converted to a float
                    scores.append(row[i])
                except:
                    user_list.append(row[i])
        user_list.append(dates)
        user_list.append(scores)
    

我想要的是一个不会在每个空白单元格中都下降到 0 的图表。我希望能做到这一点,这样空白单元格要么被忽略(对于两点之间的空白),要么只是以相同的斜率继续(对于当空白位于一组 erg 分数的末尾时)。

我用这段代码得到的是我想要的数据的正确形式,但是 y 值列表(erg 分数)比 x 值列表(Unix 时间)短,所以它在以下情况下不起作用用 matplotlib.pyplot 绘图。

如果有人有任何关于使用 pandas 或 matplotlib(或我应该研究的其他模块)的教程或技巧,以便更好地利用我的数据,我将不胜感激。我正在尝试尽可能多地学习,所以最好没有答案。

【问题讨论】:

  • 如果您使用 pandas read_csv 方法,空白单元格会自动转换为 nan,当您在 matplotlib 中绘制它们时,它们会在图表中显示为空白。如果您想要您正在寻找的空白可视化,使用read_csv 是最简单的方法。

标签: python pandas matplotlib


【解决方案1】:

最简单的方法可能是遍历转置后的 DataFrame 中的列并绘制它们,删除 NAs:

from matplotlib.dates import DateFormatter


df = pd.read_csv('scores.csv', index_col=0)
df = df.T
df.index = pd.to_datetime(df.index, unit='s')

fig, ax = plt.subplots(figsize=(10,8))

fmt = DateFormatter("%M:%S")
ax.yaxis.set_major_formatter(fmt)

for c in df.columns:
    df[c] = pd.to_datetime('1970-01-01 00:' + df[c])
    df[c].dropna().plot(ax=ax, label=c, style='.-')

ax.legend()

输出:

附:我在 unix 时间 '132753600' 中添加了另一个 '0',将其从 1974 年带到了 2012 年,以使其更符合其他记录

【讨论】:

  • 困难的问题... Coursera 上有一门课程涵盖 matplotlib (coursera.org/learn/python-plotting),我认为作为介绍还不错,对于更具体的问题,您可能最终还是会遇到 stackoverflow ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-30
  • 1970-01-01
  • 2018-11-20
相关资源
最近更新 更多