pd.DataFrame 如何将连续满足条件的多行数据进行比较,返回较大值和较小值?
import pandas as pd## the time column doesn't matter in your problem
df = pd.DataFrame({
'time':['2021-3-19','2021-3-20','2021-3-21','2021-3-22',
'2021-3-23','2021-3-24','2021-3-25','2021-3-26','2021-3-27'],
'value':[10,11,9,5,4,2,4,9,5],
'status':['X']*3+['Y']+['X']+['Y']*2+['X']*2
})
df_new = pd.DataFrame(columns=df.columns)
## perform a groupby on consecutive values
for _, g in df.groupby([(df.status != df.status.shift()).cumsum()]):
g = g.sort_values(by='value')
## keep the highest value for X
if g.status.values[0] == 'X':
g = g.drop_duplicates(subset=['status'], keep='last')
## keep the lowest value for Y
elif g.status.values[0] == 'Y':
g = g.drop_duplicates(subset=['status'], keep='first')
else:
pass
df_new = pd.concat([df_new, g])
df_new = df_new.reset_index(drop=True)
print(df_new)
————————
程序输出
time value status
0 2021-3-20 11 X
1 2021-3-22 5 Y
2 2021-3-23 4 X
3 2021-3-24 2 Y
4 2021-3-26 9 X
怎么能在原表中实现如下效果?==x 取较大值 ==y 取较小值
time value status value_1
0 2021-3-19 10 X 10
1 2021-3-20 11 X 11
2 2021-3-21 9 X 11
3 2021-3-22 5 Y 5
4 2021-3-23 4 X 4
5 2021-3-24 2 Y 2
6 2021-3-25 4 Y 2
7 2021-3-26 9 X 9
8 2021-3-27 5 X 9