数据帧列表:将数据帧切片为数据帧列表

2024-10-01 07:31:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的函数,它应该返回一个dataframes列表。这些数据帧不能包含任何已包含的值。你知道吗

idx是满足条件的索引列表(dummy=1)。 然后将假人(n)周围的所有物体都放下。你知道吗

我的输出应该是一个数据帧列表,其中包含没有删除的值,但是没有其他值(在两个虚拟对象之间)。第一个数据帧正常。我计算元素并使用for循环尝试收集其他片段,但是,片段不会返回在所需限制内的数据帧。你知道吗

data = pd.DataFrame(data={"A":[1,2,3,4,5,6,7,8,9,10], 
                          "B":[1,3,3,4,5,6,7,8,9,10],
                      "event":[0,0,0,0,1,0,0,0,1,0]})

def EstimationWindow (data, n=3, dummy=1):
    '''
    data....data. Contains ALL data - reurns, and event dummies = event column
    dummy...event=1
    n.......days before/after
    '''    
    idx = data.index.get_indexer_for(data[data.event==dummy].index)
    # Drop event window
    estwin = data.drop((np.unique(np.concatenate([np.arange(max(i-n,0), min(i+n+1, len(data))) for i in idx]))))    
#    estwin = [estwin.iloc[0:i-n] for i in idx]
    output = [estwin.iloc[0:idx[0]-n]]
    for i in idx[1:]:
        out = pd.DataFrame(estwin.loc[len(output):i-n])
        output.append(out)
    return(output)

函数应该返回一个列表:output = [df1, df2]

通缉犯:

[   A  B  event
 0  1  1      0
 1  2  3      0
 2  3  3      0,    A  B  event
 6  7  7      0]

结果:

 [   A  B  event
 0  1  1      0
 1  2  3      0
 2  3  3      0,    A  B  event
 1  2  3      0
 2  3  3      0
 6  7  7      0]

Tags: 数据函数ineventdataframe列表foroutput
1条回答
网友
1楼 · 发布于 2024-10-01 07:31:57

无需使用for循环来构造拆分df的列表。找到虚拟对象,使用^{}构建要删除的索引,只需使用直接的^{}

s = df.event.eq(1)
dummies = s[s].index

ind_to_drop = (dummies + 1).union(dummies).union(dummies - 1)
c = df.event.cumsum().drop(ind_to_drop)

那么

for _, g in df.drop(ind_to_drop).groupby(c):
    print(g)

收益率

   A  B  event
0  1  1      0
1  2  3      0
2  3  3      0

   A  B  event
6  7  7      0

相关问题 更多 >