对大于阈值的值进行计数,并将其指定给相应的年份

2024-09-30 20:23:53 发布

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

我有一个如下所示的数据帧:

Date    DFW
242 2000-05-01 00:00:00 75.92
243 2000-05-01 12:00:00 75.02
244 2000-05-02 00:00:00 71.96
245 2000-05-02 12:00:00 75.92
246 2000-05-03 00:00:00 71.96
... ... ...
14991   2020-07-09 12:00:00 93.90
14992   2020-07-10 00:00:00 91.00
14993   2020-07-10 12:00:00 93.00
14994   2020-07-11 00:00:00 89.10
14995   2020-07-11 12:00:00 97.00

df包含2000-2020年5月至7月11日期间每12小时一次特定位置的最大温度值。我想计算该值的次数>;90,然后将该值存储在行为年份的列中。我应该使用groupby来完成这项任务吗

预期产出:

Year   count
2000   x
2001   y
...   ...
2019   z
2020   a

Tags: 数据gtdfdatecount温度次数year
2条回答

一种可能的方法是提取并创建一个新的年列(比如“年”),然后

df[df['DFW'] > 90].groupby('year').count().reset_index()

您可以使用groupby

# extract the years from dates
years = df['Date'].dt.year

# compare `DFW` with `90`
# gt90 will be just True or False
gt90 = df['DFW'].gt(90)

# sum the `True` by years
output = gt90.groupby(years).sum()

# set the years as normal column:
output = output.reset_index()

所有这些都集中在一行:

df['DFW'].gt(90).groupby().sum().reset_index()

相关问题 更多 >