对df中的每一行进行操作

问题描述

如果单元格中的数字大于720且小于1080,我想为每行360减去。如何为df中的每一行执行if语句?

我尝试过:

if row in (df['position']>720 and df['position']<1080):
   df['720-1080']=(df['position']-360)

解决方法

Series.maskSeries.between一起使用时使用掩码:

df = pd.DataFrame({'position':[7000,800,1000]})

mask = df['position'].between(720,1080,inclusive=False)
#alternative
#mask =  (df['position']>720) & (df['position']<1080)
df['720-1080'] = df['position'].mask(mask,df['position'] - 360)
print (df)
   position  720-1080
0      7000      7000
1       800       440
2      1000       640