我想基于两列之间的条件按组进行行比较。此条件为:(col1(i)-col1(j))*(col2(i)-col2(j)) <= 0
,我们在列col1和col2中将每一行i与第j行进行比较。如果满足该组中所有行比较的条件,则将该组设置为true,否则设置为false。
data = {'group':['A', 'A', 'A', 'B', 'B', 'B'],
'col1':[1, 2, 3, 2, 3, 1], 'col2':[4, 3, 2, 2, 3, 1]}
df = pd.DataFrame(data)
df
带输出
A True
B False
您可以shift
与下一行进行比较,还groupby+all
可以检查组中的所有项目是否为True
:
cond=((df['col1']-df['col1'].shift(-1))*(df['col2']-df['col2'].shift(-1))<=0)&(df['group']==df['group'].shift(-1))
cond.groupby(df['group']).all()
group
A True
B False
dtype: bool
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句