gpt4 book ai didi

python - 寻找 Pandas 最长的连续增长

转载 作者:行者123 更新时间:2023-12-04 03:30:33 30 4
gpt4 key购买 nike

我有一个数据框:

Date    Price
2021-01-01 29344.67
2021-01-02 32072.08
2021-01-03 33048.03
2021-01-04 32084.61
2021-01-05 34105.46
2021-01-06 36910.18
2021-01-07 39505.51
2021-01-08 40809.93
2021-01-09 40397.52
2021-01-10 38505.49

Date object
Price float64
dtype: object

而我的目标是找到最长的连续增长期。它应该返回:最长的连续时间段是从 2021-01-04 到 2021-01-08,增加了 8725.32 美元老实说,我不知道从哪里开始。这些是我在 pandas 中的第一步,我不知道应该使用哪些工具来获取这些信息。

谁能帮我/指出正确的方向?

最佳答案

递减时用cumsum检测递增序列:

df['is_increasing'] = df['Price'].diff().lt(0).cumsum()

你会得到:

         Date     Price  is_increasing
0 2021-01-01 29344.67 0
1 2021-01-02 32072.08 0
2 2021-01-03 33048.03 0
3 2021-01-04 32084.61 1
4 2021-01-05 34105.46 1
5 2021-01-06 36910.18 1
6 2021-01-07 39505.51 1
7 2021-01-08 40809.93 1
8 2021-01-09 40397.52 2
9 2021-01-10 38505.49 3

现在,您可以检测最长的序列

sizes=df.groupby('is_increasing')['Price'].transform('size')
df[sizes == sizes.max()]

你得到:

         Date     Price  is_increasing
3 2021-01-04 32084.61 1
4 2021-01-05 34105.46 1
5 2021-01-06 36910.18 1
6 2021-01-07 39505.51 1
7 2021-01-08 40809.93 1

关于python - 寻找 Pandas 最长的连续增长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66955196/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com