Python 发现大熊猫数量最长的连续增长
我有一个数据帧:Python 发现大熊猫数量最长的连续增长,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个数据帧: 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
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美元
老实说,我不知道从哪里开始。这是我学习熊猫的第一步,我不知道应该使用哪些工具来获取这些信息
有人能帮我/给我指出正确的方向吗?用cumsum on递减来检测你的递增顺序:
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
哦,上帝,非常感谢你!我试着用diff()和cumsum()工作,但没能把它弄清楚。它起作用了!你太棒了!