Python 如何使用if语句并执行以下操作?

Python 如何使用if语句并执行以下操作?,python,pandas,if-statement,Python,Pandas,If Statement,如何使用if循环并执行以下条件: 例如,如果我有以下数据类型 id count A count B variable A variable sum AAA 6 34 AA AA 10 123 15 19 RA RA 25 AAA 61 04 AA

如何使用if循环并执行以下条件:

例如,如果我有以下数据类型

id    count A    count B    variable A     variable    sum
AAA    6           34         AA              AA        10
123    15          19         RA              RA        25
AAA    61          04         AA              AA        85
123    1           91         RS              RS        35
123    66          89         RA              RA        25
AAA    45          41         SP              SP        55
123    62          39         SS              SS        45
对于相同的id,如果变量A和变量B相同而不相同,我希望执行此操作

如果变量A=变量B

df = df.assign(result = np.where(df.sum < 50, df.shift(1).count A, df.count A))
df = df.assign(result = np.where(df.sum > 50, df.shift(1).count A, df.count A))

似乎需要使用
()
&
(和)添加条件:

m1=(df['sum']<50)和(df['variable A']==df['variable B'])
df=df.assign(结果=np.where(m1,df.shift(1)['count A'],df['count A']))
m2=(df['sum']>50)和(df['variable A']!=df['variable B'])
df=df.assign(结果=np.where(m2,df.shift(1)['count A'],df['count A']))

每种情况下的公式是否相同?也许可以考虑
df['count B']
instaed
df['count A']
m1 = (df['sum'] < 50)  & (df['variable A'] == df['variable B'])
df = df.assign(result = np.where(m1, df.shift(1)['count A'], df['count A']))

m2 = (df['sum'] > 50)  & (df['variable A'] != df['variable B'])
df = df.assign(result = np.where(m2, df.shift(1)['count A'], df['count A']))