一、前后行满足条件
问题:
回答:
df = pa.DataFrame({'产品': ['A','B','C'],
'数据1': [1, 4, 6],
'数据2': [2, 5, 3]})
df[(df['数据1'].shift(1) < df['数据2'].shift(1)) & (df['数据1'].shift(0) > df['数据2'].shift(0))]['产品']
说明:
例如:
In [75]: df = pd.DataFrame({'A':range(5), 'B':range(10,20,2)})
In [76]: df
Out[76]:
A B
0 0 10
1 1 12
2 2 14
3 3 16
4 4 18
In [77]: mask = (df['A'].shift(1) + df['B'].shift(2) > 12)
In [78]: mask
Out[78]:
0 False
1 False
2 False
3 True
4 True
dtype: bool
In [79]: df[mask]
Out[79]:
A B
3 3 16
4 4 18
二、前后行构造数据
问题:
答案:
import numpy as np
import pandas as pd
df = pd.DataFrame({'date': ['20150101','20150102','20150103','20150104','20150105','20150106'],
'A': [8,10,9,11,11,12],
'B': [7,9,8,11,10,10],
'M': [7.5,9.5,8.5,11,10.5,11],
'S': [0,-1,1,0,0,-1]})
df = df.reindex(columns=['date','A','B','M','S'])
# 方法一
df['cost'] = np.where(df['S'] < 0,
np.roll((df['M']-df['B']), 1)*df['S'],
np.where(df['S'] > 0,
np.roll((df['M']-df['A']), 1)*df['S'],
0)
)
# 方法二
M, A, B, S = [df[col] for col in 'MABS']
conditions = [S < 0, S > 0]
choices = [(M-B).shift(1)*S, (M-A).shift(1)*S]
df['cost2'] = np.select(conditions, choices, default=0)
print(df)