【问题标题】:For loop with Pandas DataFrames to fill list of data [closed]使用 Pandas DataFrames 循环填充数据列表 [关闭]
【发布时间】:2020-09-17 15:59:05
【问题描述】:

我正在编写一些代码来使用 .csv 文件绘制时间序列,但我必须绘制几年(准确地说是 2000 年到 2019 年)及其各自的月份。我尝试以这种方式使用 for 循环:

import pandas as pd
import matplotlib.pyplot as plt
c1 = pd.read_csv('D:/file.csv')
c1['Date'] = pd.to_datetime(c1['Date'], format = '%m/%d/%Y')
c1.set_index('Date', inplace=True)

year = 2000

for j in range(12):
    sets = list()
    data = c1['%s-%0d'%(year, j+1)]['Moisture']
    sets.append(data)

我想得到这样的结果:

sets = [c1['2000-01']['Moisture'], c1['2000-02']['Moisture'], ... , c1['2000-12']['Moisture']]

所以我可以用这段代码绘制我的数字:

for j in range(12):
    sets = list()
    data = c1['%s-%0d'%(year, j+1)]['Moisture']
    sets.append(data)

    plt.figure()
    plt.plot(sets[j], 'black')
    plt.title('Layer 1 (0 cm - 7 cm)')
    plt.xlabel(str(year))
    plt.ylabel(r'Moisture $(m^{3} / m^3)$')
    plt.xticks([])
    plt.savefig('D:/randomlocation.png')

我试过了,但每次都显示

IndexError: list index out of range

所以我认为它只是在列表中添加一项。我该如何解决?

【问题讨论】:

  • 你能分享一个DataFrame的例子吗?预期的输出是什么?
  • 请提供预期的minimal, reproducible example。显示中间结果与您的预期不同的地方。我们应该能够复制和粘贴您的代码的连续块,执行该文件,并重现您的问题以及跟踪问题点的输出。特别是,我们需要完整的错误消息和违规值的跟踪。
  • c1['2000-01'] 字典中的值吗?为什么需要使用链式赋值c1['2000-01']['Moisture']
  • 我已经用下面的答案解决了这个问题,只是理解for循环的问题,对不起

标签: python pandas matplotlib


【解决方案1】:

首先,您将在每次循环迭代时覆盖setssets = list() 应该移到 for 循环之外。

另外,在这里使用i 而不是j 可能是问题的一部分

plt.plot(sets[i], 'black')

【讨论】:

  • [i][j] 是错字,我的错。是的,这只是覆盖问题,谢谢。
猜你喜欢
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 2016-02-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多