代码之家  ›  专栏  ›  技术社区  ›  Gerry

在数据帧中递归引用行

  •  1
  • Gerry  · 技术社区  · 6 年前

    数据文件 df 定义如下:

    import pandas as pd
    df1 = pd.DataFrame({'A':[False,True,True,False,True,True,True,True,False,True,True], 'B':[0,0,0,2,2,1,0,0,1,0,0]}, columns=['A','B'])
    df1
            A  B
    0   False  0
    1    True  0
    2    True  0
    3   False  2
    4    True  2
    5    True  1
    6    True  0
    7    True  0
    8   False  1
    9    True  0
    10   True  0
    

    每隔一列 A False 但列中的值 B >0 然后 应该移到下一行,直到 0 . 因此,上述数据帧的期望输出是

            A  B
    0   False  0
    1    True  0
    2    True  0
    3    True  2
    4    True  2
    5    True  1
    6   False  0
    7    True  0
    8    True  1
    9   False  0
    10   True  0
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   BENY    6 年前

    IIUC

    s=(~df1.A).cumsum() 
    # get the group key 
    
    groupkey=df1.groupby(s).B.transform('first')>0
    # find whether we should include the group when the first B of the group is great than 0 or not
    
    df1.A.update(df1.loc[groupkey&(~(df1.B.gt(0)&(df1.A))),'A'].groupby(s).shift().fillna(True)) 
    # using update 
    df1
            A  B
    0   False  0
    1    True  0
    2    True  0
    3    True  2
    4    True  2
    5    True  1
    6   False  0
    7    True  0
    8    True  1
    9   False  0
    10   True  0
    

    更多信息

    ~(df1.B.gt(0)&(df1.A)) # exclude those A equal to True and B great than 0 row
    0      True
    1      True
    2      True
    3      True
    4     False
    5     False
    6      True
    7      True
    8      True
    9      True
    10     True
    dtype: bool
    
        2
  •  0
  •   cors    6 年前

    我想这不是最佳的,但至少是可行的。

    df1['to_move'] = ((df1['A']==False) & (df1['B']>0))
    indexes_to_move = list(df1[df1['to_move']].index)
    for ind in indexes_to_move:
        temp = df1.loc[ind:,'B']
        to_change = temp[temp==0].index.min()
        df1.loc[ind, 'A'] = True
        df1.loc[to_change, 'A'] = False
    del df1['to_move']