簡體   English   中英

如何計算每個唯一鍵的趨勢。 數據幀

[英]how to figure out trend per unique key. dataframe

我有一個帶2個cols的DataFrame

ColA| ColB 
D 2 
D 12 
D 15 
A 20 
A 40 
A 60 
C 60 
C 55 
C 70 
C 45 
L 45 
L 23 
L 10 
L 5

結果/輸出將是

D UP
A UP
C FLAT
L Down
其中UP是將所有相關權重相加的結果:每個密鑰的每個連續權重必須小於先前的權重。 你必須擁有UP的例子

這是一個簡單的技術,可能不適合所有情況,即:

def sum_t(x):
    # Compare the value with previous value
    m = x > x.shift() 
    # If all of them are increasing then return Up
    if m.sum() == len(m)-1:
        return 'UP'
    # if all of them are decreasing then return Down
    elif m.sum() == 0:
        return 'DOWN'
    # else return flat
    else:
        return 'FLAT'

df.groupby('ColA')['ColB'].apply(sum_t)

輸出:

ColA
A      UP
C    FLAT
D      UP
L    DOWN
Name: ColB, dtype: object

使用diffcrosstab

s=df.groupby('ColA').ColB.diff().dropna()#Dropna since the first value for all group is invalid 
pd.crosstab(df.ColA.loc[s.index],s>0,normalize = 'index' )[True].map({1:'Up',0:'Down'}).fillna('Flat')
Out[100]:
ColA
A      Up
C    Flat
D      Up
L    Down
Name: True, dtype: object

改變為@ Dark的想法,我首先計算GroupBy + diff然后在輸入自定義函數之前使用unique

然后使用基於min / max邏輯。

def calc_label(x):
    if min(x) >= 0:
        return 'UP'
    elif max(x) <= 0:
        return 'DOWN'
    else:
        return 'FLAT'

res = df.assign(C=df.groupby('ColA').diff().fillna(0))\
        .groupby('ColA')['C'].unique()\
        .apply(calc_label)

print(res)

ColA
A      UP
C    FLAT
D      UP
L    DOWN
Name: C, dtype: object

在自定義def使用numpy.polyfit

通過這種方式,您可以調整您將被稱為“FLAT”的漸變

def trend(x, flat=3.5):
    m = np.polyfit(np.arange(1, len(x)+1), x, 1)[0]
    if abs(m) < flat:
        return 'FLAT'
    elif m > 0:
        return 'UP'
    return 'DOWN'

df.groupby('ColA')['ColB'].apply(np.array).apply(trend)

解決方法是對每個ID關聯點應用線性回歸,並通過二維空間中id關聯點的斜率指定趨勢

import numpy as np
from sklearn import linear_model
def slope(x,min_slope,max_slope):
    reg = linear_model.LinearRegression()
    reg.fit(np.arange(len(x),x))
    slope =  reg.coef_[0][0]
    if slope < min_slope:
        return 'Down'
    if slope > max_slope:
         return 'Up'
    else 'Flat'
min_slope = -1
max_slope = 1
df['slopes'] = df.groupby('ColA').apply(lambda x: slope(x['ColB'],min_slope,max_slope))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM