【问题标题】:Count number of days in a row with weather above certain temp with pandas用熊猫连续计算天气高于特定温度的天数
【发布时间】:2020-05-14 17:48:30
【问题描述】:

所以我有一个每日天气数据的数据框,如果温度高于 0。例如:

|日期|温度|pos_temp|

我正在尝试创建一个列,该列在温度高于零的情况下连续几天累积总和。我在 0 以上的天数中创建了一个 1 或 0 的 one-hot 编码列,但是我在计算“正”列中的“1”的累积天数时遇到了麻烦。

例子

date      |temp|pos_temp|
2020-04-27|1   |1       |
2020-04-28|-1  |0       | 
2020-04-29|-2  |0       |
2020-04-30|4   |1       |
2020-05-01|7   |1       |
2020-05-02|10  |1       | 
2020-05-03|14  |1       |
2020-05-04|13  |1       |

我正在尝试制作这样的专栏:

date      |temp|pos_temp|cum_above_0
2020-04-27|1   |1       |nan
2020-04-28|-1  |0       |0
2020-04-29|-2  |0       |0
2020-04-30|4   |1       |1
2020-05-01|7   |1       |2
2020-05-02|10  |1       |3
2020-05-03|14  |1       |4
2020-05-04|13  |1       |5

【问题讨论】:

  • 你能在这个问题中添加一些示例数据和预期输出吗?
  • 我建议两个步骤:首先实现一个行/数据集,其中高于零和零,低于零。其次,只需在系列中实现一个循环,在满足条件时增加“某个总和”,如果不满足,则将“某个总和”重置/保持为零。之后,您可以将数据添加到 Pandas 工作表中。

标签: python pandas pandas-groupby cumsum


【解决方案1】:

您可以迭代数据框的每一行。

temp = pd.DataFrame({'temp':[1, -1, -2, 4, 7, 10, 14, 13]})

count = 0

for index, row in temp.iterrows():
    if row['temp'] > 0:
        count += 1
    else:
        count = 0
    temp.loc[index, 'cum_above_0'] = count



   temp   cum_above_0
0   1     1.0
1   -1    0.0
2   -2    0.0
3   4     1.0
4   7     2.0
5   10    3.0
6   14    4.0
7   13    5.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    相关资源
    最近更新 更多