pandas:设置多索引的最后N行为Nan,用shift加速groupby



我想加快我的分组速度。应用+ shift和感谢之前的问答:如何加快Pandas多级数据帧分组迁移?我可以证明,当你有很多组时,它确实可以加快速度。

从这个问题中,我现在有了下面的代码来将每个多索引中的第一个条目设置为Nan。现在我可以在全球范围内轮班,而不是每个小组。

df.iloc[df.groupby(level=0).size().cumsum()[:-1]] = np.nan

但是我想向前看,而不是向后看,并且需要跨N行进行计算。所以我试图使用一些类似的代码来设置最后N个条目NaN,但显然我错过了一些重要的索引知识,因为我只是不能弄清楚。

我想把它转换成一个范围,而不是一个整数。我该怎么做呢?

 # the start of each group, ignoring the first entry
 df.groupby(level=0).size().cumsum()[1:]

测试设置(对于向后移位)如果你想尝试:

length = 5
groups = 3
rng1 = pd.date_range('1/1/1990', periods=length, freq='D')
frames = []
for x in xrange(0,groups):
    tmpdf = pd.DataFrame({'date':rng1,'category':int(10000000*abs(np.random.randn())),'colA':np.random.randn(length),'colB':np.random.randn(length)})
    frames.append(tmpdf)
df = pd.concat(frames)
df.sort(columns=['category','date'],inplace=True)
df.set_index(['category','date'],inplace=True,drop=True)
df['tmpShift'] = df['colB'].shift(1)
df.iloc[df.groupby(level=0).size().cumsum()[:-1]] = np.nan
# Yay this is so much faster.
df['newColumn'] = df['tmpShift'] / df['colA']
df.drop('tmp',1,inplace=True)

谢谢!

我最终使用groupby应用程序,如下所示(并编码为向前或向后工作):

def replace_tail(grp,col,N,value):
    if (N > 0):
        grp[col][:N] = value
    else:
        grp[col][N:] = value
    return grp
df = df.groupby(level=0).apply(replace_tail,'tmpShift',2,np.nan)
所以最后的代码是:
def replace_tail(grp,col,N,value):
    if (N > 0):
        grp[col][:N] = value
    else:
        grp[col][N:] = value
    return grp

length = 5
groups = 3
rng1 = pd.date_range('1/1/1990', periods=length, freq='D')
frames = []
for x in xrange(0,groups):
    tmpdf = pd.DataFrame({'date':rng1,'category':int(10000000*abs(np.random.randn())),'colA':np.random.randn(length),'colB':np.random.randn(length)})
    frames.append(tmpdf)
df = pd.concat(frames)
df.sort(columns=['category','date'],inplace=True)
df.set_index(['category','date'],inplace=True,drop=True)
shiftBy=-1
df['tmpShift'] = df['colB'].shift(shiftBy)
df = df.groupby(level=0).apply(replace_tail,'tmpShift',shiftBy,np.nan)
# Yay this is so much faster.
df['newColumn'] = df['tmpShift'] / df['colA']
df.drop('tmpShift',1,inplace=True)

最新更新