仅从匹配datetim的numpy数组中获取元素

2024-06-16 11:07:59 发布

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

我有一个潮汐高度数据列表,每10分钟读取一次,持续1年,我已经从csv加载到列表中。你知道吗

我试图实现的最终结果是能够(直线或条形)绘制潮汐图,最终得到如下结果: https://nt.gov.au/__data/assets/pdf_file/0020/430238/2018-mar-tidal-info-ntports-centre-island-graph.pdf

我对编程相当陌生,给自己设定了一个较小的任务,即根据给定日期的高度数据创建潮汐图。然后我会输出多个图表来组成一周等等

 # import numpy as np
 # from datetime import datetime
        DATA:
            010120170010  1.700        
            010120170020  1.650    

    for line in csv_reader:    
        data_times.append(datetime.strptime(line[0], "%d%m%Y%H%M"))
        data_height.append(float(line[2]))

    np_data_times = np.array(data_times)
    np_data_height = np.array(data_height)

仅使用今天的高度创建阵列 有没有更好的方法来实现python与SQL的等价关系 '选择*from times where date=today()'? 我可以用time:height而不是2个数组创建字典吗?(我读到过,dicts是无序的,所以远离这种方法)

每6小时划分一次绘图数组 我还想提供数据点的图表,但只显示时间除以每3或6小时跨X轴。这将提供一个更平滑和更准确的图形。到目前为止,我只知道如何给数据的x轴和它的标签在1:1的方式,当我可能需要6:1或18:1等,有没有一个特别的方法,我应该看看?你知道吗

# import matplotlib.pyplot as plt
plt.title("Tides for today")
plt.xlabel(datetime.date(real_times[0]))
plt.ylabel("Tide Height")
plt.plot(real_times, real_heights)
plt.show()

Tags: csv数据方法import列表datadatetime高度
1条回答
网友
1楼 · 发布于 2024-06-16 11:07:59

不要用字典。这会使一切变得缓慢和难以处理。
我建议考虑使用pandas。你知道吗

读取数据的方式如下:

import pandas as pd
from datetime import datetime

conv={"Time" : lambda t: datetime.strptime(t, "%d%m%Y%H%M")}
df = pd.read_csv("datafile.txt", header=None, delim_whitespace=True, 
                 names=["Time", "Tide"], converters=conv,index_col=0 )

结果是

                     Tide
Time                     
2017-01-01 00:10:00  1.70
2017-01-01 00:20:00  1.65
2017-01-01 05:20:00  1.35
2017-01-02 00:20:00  1.75

您现在可以filter the dataframe,例如,仅选择1月1日的数据:

df["2017-01-01":"2017-01-01"] 

你可以像这样直接绘制数据

df["2017-01-01":"2017-01-01"].plot(kind="bar")

或者

df["2017-01-01 00:00":"2017-01-01 06:00"].plot(kind="bar")

如果时间间隔相等,这将很好地工作,因为它创建了一个分类条形图。(请记住,如果在脚本中工作,可能需要使用pyplot.show()

也可以使用matplotlib绘制条形图

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates

df1 = df["2017-01-01 00:00":"2017-01-01 06:00"]
plt.bar(df1.index,df1.Tide, 
        width=np.diff(matplotlib.dates.date2num(df1.index.to_pydatetime()))[0], ec="k")
plt.show()

要获得对xaxis记号和标签的控制权,后面的matplotlib解决方案将是一个不错的选择。首先设置条与边对齐,align="edge"。 然后使用格式化程序和定位器,如official dates example中所示。可以使用plt.grid定义网格。你知道吗

plt.bar(df1.index,df1.Tide, 
        width=np.diff(matplotlib.dates.date2num(df1.index.to_pydatetime()))[0], 
        align="edge", ec="k")

hours = matplotlib.dates.HourLocator()   # every hour
#hours = matplotlib.dates.HourLocator(byhour=range(24)[::3]) # every 3 hours
fmthours=matplotlib.dates.DateFormatter("%m-%d %H:%M")
plt.gca().xaxis.set_major_locator(hours)
plt.gca().xaxis.set_major_formatter(fmthours)

plt.grid(True, axis="x", linewidth=1, color="k")
plt.gcf().autofmt_xdate()
plt.show()

然后可能会出现以下情况: enter image description here

相关问题 更多 >