簡體   English   中英

Pandas計數值大於最后n行中的當前行

[英]Pandas count values greater than current row in the last n rows

如何獲得大於最后n行中當前行的值的計數?

想象一下,我們有一個數據幀如下:

    col_a
0    8.4
1   11.3
2    7.2
3    6.5
4    4.5
5    8.9

我試圖得到一個表,如下面的n = 3。

    col_a   col_b
0     8.4       0
1    11.3       0
2     7.2       2
3     6.5       3
4     4.5       3
5     8.9       0

提前致謝。

在熊貓中最好不要循環因為速度慢,這里最好使用自定義函數rolling

n = 3
df['new'] = (df['col_a'].rolling(n+1, min_periods=1)
                        .apply(lambda x: (x[-1] < x[:-1]).sum())
                        .astype(int))
print (df)
   col_a  new
0    8.4    0
1   11.3    0
2    7.2    2
3    6.5    3
4    4.5    3
5    8.9    0

如果性能很重要,請使用步幅

n = 3
x = np.concatenate([[np.nan] * (n), df['col_a'].values])

def rolling_window(a, window):
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
arr = rolling_window(x, n + 1)

df['new'] = (arr[:, :-1] > arr[:, [-1]]).sum(axis=1)
print (df)
   col_a  new
0    8.4    0
1   11.3    0
2    7.2    2
3    6.5    3
4    4.5    3
5    8.9    0

性能 :這里用於小窗口n = 3 perfplot

G1

np.random.seed(1256)
n = 3

def rolling_window(a, window):
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

def roll(df):
    df['new'] = (df['col_a'].rolling(n+1, min_periods=1).apply(lambda x: (x[-1] < x[:-1]).sum(), raw=True).astype(int))
    return df

def list_comp(df):
    df['count'] = [(j < df['col_a'].iloc[max(0, i-3):i]).sum() for i, j in df['col_a'].items()]
    return df

def strides(df):
    x = np.concatenate([[np.nan] * (n), df['col_a'].values])
    arr = rolling_window(x, n + 1)
    df['new1'] = (arr[:, :-1] > arr[:, [-1]]).sum(axis=1)
    return df


def make_df(n):
    df = pd.DataFrame(np.random.randint(20, size=n), columns=['col_a'])
    return df

perfplot.show(
    setup=make_df,
    kernels=[list_comp, roll, strides],
    n_range=[2**k for k in range(2, 15)],
    logx=True,
    logy=True,
    xlabel='len(df)')

我也很好奇大窗口的性能, n = 100

G2

n = 3
df['col_b'] = df.apply(lambda row: sum(row.col_a <= df.col_a.loc[row.name - n: row.name-1]), axis=1)

Out[]: 
   col_a  col_b
0    8.4      0
1   11.3      0
2    7.2      2
3    6.5      3
4    4.5      3
5    8.9      0

使用pd.Series.items的列表理解:

n = 3
df['count'] = [(j < df['col_a'].iloc[max(0, i-3):i]).sum() \
               for i, j in df['col_a'].items()]

等價地,使用enumerate

n = 3
df['count'] = [(j < df['col_a'].iloc[max(0, i-n):i]).sum() \
               for i, j in enumerate(df['col_a'])]

結果:

print(df)

   col_a  count
0    8.4      0
1   11.3      0
2    7.2      2
3    6.5      3
4    4.5      3
5    8.9      0

暫無
暫無

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

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