如何使用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))
如果变量A!=变量B
df = df.assign(result = np.where(df.sum > 50, df.shift(1).count A, df.count A))
答案 0 :(得分:0)
您似乎需要使用()
和&
(和)添加条件:
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']))