对于以下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 ….等N列与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')