鍍金池/ 問(wèn)答/數(shù)據(jù)分析&挖掘  Python/ 如何用pandas尋找一些持續(xù)增長(zhǎng)的數(shù)值?

如何用pandas尋找一些持續(xù)增長(zhǎng)的數(shù)值?

數(shù)據(jù)結(jié)構(gòu)如下
日期        ID      數(shù)據(jù)1      數(shù)據(jù)2
2018-3-8   001      68        199
2018-3-8   002      72        288
2018-3-9   001      71        85  
2018-3-9   002      84        199
....

核心需求其實(shí)是從海量的ID中,尋找符合條件的ID。
其實(shí)問(wèn)題可以簡(jiǎn)化成為“尋找最近3天內(nèi)有連續(xù)增長(zhǎng)的ID”

請(qǐng)問(wèn)如何使用pandas尋找出以下兩種情況:

  1. 連續(xù)3天【數(shù)據(jù)1】增長(zhǎng)都大于0小于100的ID。
  2. 連續(xù)3天【數(shù)據(jù)2】都增長(zhǎng)大于5%的ID
  3. 連續(xù)3天【數(shù)據(jù)1】增長(zhǎng)大大于0小于5且【數(shù)據(jù)2】都增長(zhǎng)大于3%的ID
回答
編輯回答
囍槑
import pandas as pd
df = pd.DataFrame([['2018-3-8', 10],
    ['2018-3-9', 20],
    ['2018-3-10', 30],
    ['2018-3-11', 40],
    ['2018-3-12', 250],
    ['2018-3-13', 260],
    ['2018-3-14', 270],
    ['2018-3-15', 280]], columns=['日期', '數(shù)據(jù)1'])


def f(df):
    return (df[2] - df[1] < 100) and df[2] > df[1] and (df[1] - df[0] < 100) and df[1] > df[0] #增長(zhǎng)大于0小于100

df[pd.rolling_apply(df, window=3, func=f)['數(shù)據(jù)1'] == True] # 滿足條件的日期(展示的是連續(xù)三天的最后一天)

判斷每個(gè)ID是否有連續(xù)3天【數(shù)據(jù)1】增長(zhǎng)都大于0小于100的日期吧。

2017年5月16日 18:44