簡體   English   中英

python3中的有序數字序列

[英]sequence of ordered numbers in python3

我想生成與其他列表長度相同的有序數字序列。 我努力了

def parse_data_from_file(filename):
    times = []
    temperatures = []

    with open(filename) as csvfile:
        reader = csv.reader(csvfile, delimiter=',')
        next(reader)
        
        for row in reader:
            times.append(row[0])
            temperatures.append(float(row[1]))
            
    return times, temperatures

問題是時間沒有在 x 軸上正確表示,如下所示:

在此處輸入圖像描述

你還沒有說你是如何制作情節的。 我假設您使用的是matplotlib ,它可能是 Python 最流行的繪圖包。

我知道在處理日期或時間時,我通常使用datetime.strptime()將數據轉換為 Python 喜歡的日期時間格式:

from datetime import datetime

# assume your date info looks like 08-Jun-2022 14:22:22
dt = datetime.strptime(row[0], '%d-%b-%Y %H:%M:%S')
times.append(dt)

Matplotlib 有一個方便的函數date2num ,可以將 datetime 對象轉換為它喜歡使用的格式。 他們的官方例子在這里 這是一個更簡短的示例:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib

fig, ax = plt.subplots()
t = matplotlib.dates.date2num(times)
y = temperatures
ax.plot(t, y)
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=(1, 7)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM