【问题标题】:How to fill DataFrame column with minimum values of next n entries of other column如何用其他列的下 n 个条目的最小值填充 DataFrame 列
【发布时间】:2018-07-30 03:03:48
【问题描述】:

我有一个数据框:

import numpy as np
import pandas as pd
np.random.seed(18)
df = pd.DataFrame(np.random.randint(0,50,size=(10, 2)), columns=list('AB'))
df['Min'] = np.nan
n = 3   # can be changed

我需要用“B”列的下 n 个条目的最小值填充“Min”列:

目前我使用迭代:

for row in range (0, df.shape[0]-n):
    low = []
    for i in range (1, n+1):
        low.append(df.loc[df.index[row+i], 'B'])
    df.loc[df.index[row], 'Min'] = min(low)

但这是一个相当缓慢的过程。请问有没有更有效的方法?谢谢。

【问题讨论】:

    标签: python performance pandas dataframe


    【解决方案1】:

    使用rollingmin,然后使用shift

    df['Min'] = df['B'].rolling(n).min().shift(-n)
    print (df)
        A   B   Min
    0  42  19   2.0
    1   5  49   2.0
    2  46   2  17.0
    3   8  24  17.0
    4  34  17  11.0
    5   5  21   4.0
    6  47  42   1.0
    7  10  11   NaN
    8  36   4   NaN
    9  43   1   NaN
    

    如果性能很重要,请使用this solution:

    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(df['B'].values, n).min(axis=1)
    df['Min'] = np.concatenate([arr[1:], [np.nan] * n])
    print (df)
        A   B   Min
    0  42  19   2.0
    1   5  49   2.0
    2  46   2  17.0
    3   8  24  17.0
    4  34  17  11.0
    5   5  21   4.0
    6  47  42   1.0
    7  10  11   NaN
    8  36   4   NaN
    9  43   1   NaN
    

    【讨论】:

      【解决方案2】:

      Jez 明白了。作为另一种选择,您还可以在系列中进行前滚操作(如 Andy here 建议的那样)

      df.B[::-1].rolling(3).min()[::-1].shift(-1)
      
      0     2.0
      1     2.0
      2    17.0
      3    17.0
      4    11.0
      5     4.0
      6     1.0
      7     NaN
      8     NaN
      9     NaN
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-14
        • 1970-01-01
        • 2022-11-16
        • 2017-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多