每年数据帧值的绘图频率

2024-04-25 11:44:35 发布

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

我有一个数据框,其中包含1990-2019年25个不同地点的每小时温度数据。我想计算某个值高于或低于某个阈值的小时数,然后将该值绘制为每年的小时数总和。我知道我可以使用条形图或柱状图进行绘图,但不确定如何汇总数据以执行此任务

数据帧:

time                 Antwerp       Rotterdam  ...
1990-01-01 00:00:00  2             4          ...
1990-01-01 01:00:00  3             4          ...
1990-01-01 02:00:00  2             4          ...
...              

我需要使用groupby函数吗

示例数据以证明:

time                    Antwerp Rotterdam   Los Angeles
0   1990-01-01 00:00:00 0       2           15
1   1990-01-01 01:00:00 1       4           14
2   1990-01-01 02:00:00 3       5           15
3   1990-01-01 03:00:00 2       6           16

现在我在寻找1990年一个城市等于或小于5度的小时数。预期产出:

time    Antwerp Rotterdam   Los Angeles
1990    4       3           0

理想情况下,我希望能够选择我想要的任何温度值


Tags: 数据time绘制阈值温度条形图小时地点
2条回答

这是不使用pandas函数的

# get the time column as a list by timelist = list(df['time'])
def get_hour_ud(df, threshold):
    # timelist = list(df['time'])
    # df['time'] = ['1990-01-01 00:00:00', '1990-01-01 01:00:00', '1990-01-01 02:00:00'] # remove this line
    timelist = list(df['time'])
    hour_list = [int(a.split(' ')[1].split(':')[0]) for a in timelist]
    up_cnt = sum(a>threshold for a in hour_list)
    low_cnt = sum(a<threshold for a in hour_list)
    print(up_cnt)
    print(low_cnt)
    return up_cnt, low_cnt

我认为您需要DatetimeIndex,比较,例如,按^{}计算更大的值,然后按聚合sum计算True的值:

df['time'] = pd.to_datetime(df['time'])
df = df.set_index('time')

N = 2
df = df.gt(N).groupby(df.index.year).sum()
print (df)
      Antwerp  Rotterdam
time                    
1990      0.0        1.0
1991      1.0        2.0

如果想要低或同等使用^{}

N = 3
df = df.le(N).groupby(df.index.year).sum()
print (df)
      Antwerp  Rotterdam
time                    
1990      1.0        0.0
1991      2.0        0.0

相关问题 更多 >