pandas 计算的值大于最后n行中的当前行 [英] Pandas count values greater than current row in the last n rows

查看:88
本文介绍了 pandas 计算的值大于最后n行中的当前行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取最近n行中大于当前行的值的计数?

How to get count of values greater than current row in the last n rows?

想象一下,我们有一个如下所示的数据框:

Imagine we have a dataframe as following:

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

我正在尝试获取一个表格,如下所示,其中n = 3.

I am trying to get a table such as following where 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

谢谢.

推荐答案

在熊猫中最好不要循环,因为它比较慢,最好使用

In pandas is best dont loop because slow, here is better use rolling with custom function:

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

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

If performance is important, use strides:

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

性能:在小窗口 perfplot >:

Performance: Here is used perfplot in small window n = 3:

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:

Also I was curious about performance in large window, n = 100:

这篇关于 pandas 计算的值大于最后n行中的当前行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆