从大型csv-fi创建时间序列图

2024-04-23 12:19:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大的csv文件,里面有3个月的温度数据。第1列是月,第2列是日,第3列是小时,第4列是分钟,第5列是温度。我试图用x轴上列出的日期/月份来绘制所有3个月的温度数据。以下是我目前所掌握的情况:

filename ='TemperatureFile.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

    month, day, hour, temperature = [], [], [], []
    for row in reader:
        mon=datetime.strptime(row[0],"%m")
        month.append(mon)
        date=datetime.strptime(row[1],"%d")
        day.append(date)
        hourx=datetime.strptime(row[2],"%H:%M")
        hour.append(hourx)
        temp = float(row[3])
        temperature.append(temp)

        datefinal=date.isoformat(month, day)


    #date.isoformat(months, days).isoformat()==    

    fig = plt.figure(dpi=128, figsize=(10,6))
    plt.plot(datefinal,temperature, c='red')

    plt.title("Temperatures", fontsize=20)
    plt.xlabel('Date', fontsize=16)
    plt.ylabel('Temperatures(F)', fontsize=16)

    plt.show()

我不知道如何组合所有的月/日/小时/分钟信息,所以所有的数据图,我也不知道如何将月/日放在x轴上。在


Tags: csv数据datetimedateplt温度readerrow
2条回答

为了让你展示的代码能正常工作,我不得不花了不少时间。在

然后我可以从3列中创建一个日期。在

最后,我将重点放在绘图的格式上。在

真的有两个问题。在

filename ='TemperatureFile.csv'

with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

    dates_list, temperature = [], []
    for row in reader:
        #Convert your 3 colums of strings into a sinlge datestring.
        datestring = ("{0:}/{1:} {2:}".format(*row))
        # Then convert that into a complete date object
        date_obj = datetime.datetime.strptime(datestring, "%m/%d %H:%M")
        # Get the temperature as before
        temp = float(row[3])
        # Add new date and temp to appropriate lists
        temperature.append(temp)
        dates_list.append(date_obj)

# Now have complete lists of date and temp.
# Next focus on the formatting of the plot.
myFmt = mdates.DateFormatter('%m/%d') # set the format to print the dates in.
months = mdates.MonthLocator()  # every month
days = mdates.DayLocator()   # every Day

fig = plt.figure(dpi=128, figsize=(10,6))
ax = fig.add_axes([0.1, 0.2, 0.85, 0.75])
plt.plot(dates_list,temperature, c='red')

# format the ticks
ax.xaxis.set_major_formatter(myFmt)    
ax.xaxis.set_major_locator(months)
ax.xaxis.set_minor_locator(days)

plt.title("Temperatures", fontsize=20)
plt.xlabel('Date', fontsize=16)
plt.ylabel('Temperatures(F)', fontsize=16)

plt.show()

如需有关如何设置绘图格式的详细信息,请通过谷歌或搜索“你想做什么”和单词matplotlib。这就是我的例子。在

如果你真的需要从部件创建一个日期时间,你可以这样做:

dtms = []
temps = []

for row in reader:
    # split row into its 4 parts
    month, day, hour, temperature = row

    # create base datetime object with the current date/time
    dt = datetime.now()

    # replace current month
    dt = dt.replace(month=int(month))

    # replace current day
    dt = dt.replace(day=int(day))

    ## or, you could replace both at the same time
    #dt = dt.replace(month=int(month), day=int(day))

    # get date object from datetime
    dt = dt.date()

    # get time
    tm = datetime.strptime(hour, "%H:%M")

    # get time object from datetime
    tm = tm.time()

    # combine date and time
    dtm = datetime(dt, tm)

    # add datetime to list
    dtms.append(dtm)

    # add temperature to list
    temps.append(float(temperature))

然而,在你的情况下似乎没有必要。实际上,一次只创建一个datetime对象要容易得多,而不是创建基本datetime对象并添加新部分:

^{pr2}$

相关问题 更多 >