我有一个数据框,其中包含从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
理想情况下,我希望能够选择我想要的任何温度值。
发布于 2020-03-29 13:01:16
我认为您需要进行比较、比较,例如DatetimeIndex
by DataFrame.gt
,然后通过聚合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
如果想要更低或相等,请使用DataFrame.le
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
发布于 2020-03-29 13:04:32
这不需要使用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
https://stackoverflow.com/questions/60914587
复制相似问题