对于下面的df
A B ..... THRESHOLD
DATE
2011-01-01 NaN NaN ..... NaN
2012-01-01 -0.041158 -0.161571 ..... 0.329038
2013-01-01 0.238156 0.525878 ..... 0.110370
2014-01-01 0.606738 0.854177 ..... -0.095147
2015-01-01 0.200166 0.385453 ..... 0.166235
我必须比较 N 个列,如 A、B、C .... 与 THRESHOLD 并输出结果,如
df['A_CALC'] = np.where(df['A'] > df['THRESHOLD'], 1, -1)
df['B_CALC'] = np.where(df['B'] > df['THRESHOLD'], 1, -1)
如何将以上内容应用于所有列(A、B、C ...)而不明确为每列编写一个语句?
最佳答案
你可以使用df.apply
:
In [670]: df.iloc[:, :-1]\
.apply(lambda x: np.where(x > df.THRESHOLD, 1, -1), axis=0)\
.add_suffix('_CALC')
Out[670]:
A_CALC B_CALC
Date
2011-01-01 -1 -1
2012-01-01 -1 -1
2013-01-01 1 1
2014-01-01 1 1
2015-01-01 1 1
如果 THRESHOLD
不是您的最后一列,您最好使用
df[df.columns.difference(['THRESHOLD'])].apply(lambda x: np.where(x > df.THRESHOLD, 1, -1), axis=0).add_suffix('_CALC')
关于python - 如何将所有列与 Pandas 中的一列进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45527834/