我有一个只包含数字数据的Dataframe:
[ In1]: df = pd.DataFrame(np.random.randn(5, 3).round(2), columns=['A', 'B', 'C'])
df
[Out1]: A B C
0 -0.27 1.22 1.10
1 -3.22 0.48 -1.64
2 1.42 0.24 -0.12
3 -1.12 0.44 0.23
4 1.88 -0.38 0.62
如何在保留符号的同时为每行 Select 绝对值的最大值?
在这种情况下,它将是:
0 1.22
1 -3.22
2 1.42
3 -1.12
4 1.88
我已经决定使用哪一列了:
[ In2]: loc_max = df.abs().idxmax(axis=1)
loc_max
[Out2]:
0 B
1 A
2 A
3 A
4 A
性能很重要,因为我的实际数据帧很大.
SOLUTIONS COMPARISON:个
下面的所有答案都将给出预期的结果.
稍微大一点的数据帧上的性能比较:
df = pd.DataFrame(np.random.randn(1000, 100).round(2))
def numpy_argmax():
idx_max = np.abs(df.values).argmax(axis=1)
val = df.values[range(len(df)), idx_max]
return pd.Series(val, index=df.index)
def check_sign():
row_max = df.abs().max(axis=1)
return row_max * (-1) ** df.ne(row_max, axis=0).all(axis=1)
def loop_rows():
return df.apply(lambda s: s[s.abs().idxmax()], axis=1)
def pandas_loc():
s = df.abs().idxmax(axis=1)
val = [df.loc[x, y] for x, y in zip(s.index, s)]
return pd.Series(val, index=df.index)
%timeit numpy_argmax()
%timeit check_sign()
%timeit loop_rows()
%timeit pandas_loc()
结果:
和往常一样,pandas
幕后的numpy
级表现最好.(如果不总是这样,请告诉我.)