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

use*_*196 2 python python-2.7 pandas

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

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

我希望输出为:

A     B     C
True  25    
False 22   44
True  55   55
False 35   70
Run Code Online (Sandbox Code Playgroud)

当列A中的尾随行为 False时,列C 与列B相同,而当列A中的尾随行为真时,列C为列B*2 ?

And*_*den 6

您可以使用whereSeries方法:

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'])
Run Code Online (Sandbox Code Playgroud)

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

In [21]: frame.apply(lambda x: 2 * x['b'] if x['a'] else x['b'], axis=1
Run Code Online (Sandbox Code Playgroud)

由于您使用的是"尾随行",因此您需要使用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
Run Code Online (Sandbox Code Playgroud)

并使用相反的方式:

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
Run Code Online (Sandbox Code Playgroud)

并且要更改第一行(例如更改为NaN,在pandas中我们使用NaN来丢失数据)

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
Run Code Online (Sandbox Code Playgroud)