df.B > 0产生系列,例如:
0 True # 4 > 0 => True1 True # 2 > 0 => True2 True # ...3 True4 True5 True6 True7 True8 False # 0 is not > 0 => False9 False # 0 is not > 0 => False...
返回多个值导致歧义(一些为True,另一些为False)。
一种解决方案是使用
np.where:
sentinel = np.nan # Or 0 if you must...df = df.assign(C=np.where(df['B'] != 0, df['A'] / df['B'], sentinel))>>> df A B C0 2 4 0.51 0 2 0.02 1 2 0.53 4 4 1.04 1 1 1.05 4 4 1.06 2 4 0.57 1 2 0.58 4 0 NaN # NaN is assigned in cases where the value in Column `B` is zero.9 1 0 NaN...



