首页 文章

在基于尾随行的pandas数据帧中进行计算

提问于
浏览
2

是否可以根据不同列中的尾随行在pandas数据框中进行计算?像这样的东西 .

frame = pd.DataFrame({'a' : [True, False, True, False],
                  'b' : [25, 22, 55, 35]})

我希望输出为:

A     B     C
True  25    
False 22   44
True  55   55
False 35   70

当列A中的 trailing row 为False时,列C与列B相同,当列A中的 trailing row 为真时,列C为列B * 2?

1 回答

  • 6

    您可以使用where Series方法:

    In [11]: frame['b'].where(frame['a'], 2 * frame['b'])
    Out[11]:
    0    25
    1    44
    2    55
    3    70
    Name: b, dtype: int64
    
    In [12]: frame['c'] = frame['b'].where(frame['a'], 2 * frame['b'])
    

    或者你可以使用apply(但这通常会更慢):

    In [21]: frame.apply(lambda x: 2 * x['b'] if x['a'] else x['b'], axis=1
    

    由于您使用的是"trailing row",因此需要使用shift

    In [31]: frame['a'].shift()
    Out[31]:
    0      NaN
    1     True
    2    False
    3     True
    Name: a, dtype: object
    
    In [32]: frame['a'].shift().fillna(False)  # actually this is not needed, but perhaps clearer
    Out[32]:
    0    False
    1     True
    2    False
    3     True
    Name: a, dtype: object
    

    并使用相反的方式:

    In [33]: c = (2 * frame['b']).where(frame['a'].shift().fillna(False), frame['b'])
    
    In [34]: c
    Out[34]:
    0    25
    1    44
    2    55
    3    70
    Name: b, dtype: int64
    

    并更改第一行(例如更改为NaN,in pandas we use NaN for missing data

    In [35]: c = c.astype(np.float)  # needs to accept NaN
    
    In [36]: c.iloc[0] = np.nan
    
    In [36]: frame['c'] = c
    
    In [37]: frame
    Out[37]:
           a   b   c
    0   True  25 NaN
    1  False  22  44
    2   True  55  55
    3  False  35  70
    

相关问题