发现大Pandas数量最长的连续增长

2024-09-29 21:59:14 发布

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

我有一个数据帧:

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

我的目标是找到最长的连续增长期。 它应返回: Longest consecutive period was from 2021-01-04 to 2021-01-08 with increase of $8725.32 老实说,我不知道从哪里开始。这是我学习熊猫的第一步,我不知道应该使用哪些工具来获取这些信息

有人能帮我指出正确的方向吗


Tags: to数据from目标datelongestobjectwith
2条回答

使用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

类似于Quang所做的拆分组,然后选择组数

s = df.Price.diff().lt(0).cumsum()
out = df.loc[s==s.value_counts().sort_values().index[-1]]
Out[514]: 
         Date     Price
3  2021-01-04  32084.61
4  2021-01-05  34105.46
5  2021-01-06  36910.18
6  2021-01-07  39505.51
7  2021-01-08  40809.93

相关问题 更多 >

    热门问题