<p>将<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer">^{<cd1>}</a>与<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="nofollow noreferrer">^{<cd2>}</a>一起使用:</p>
<pre><code>np.random.seed(111)
df_input = pd.DataFrame(np.random.randint(10, size=(10, 10)), columns=list('abcdefghij'))
print (df_input)
a b c d e f g h i j
0 6 8 3 6 6 7 1 8 3 4
1 5 4 3 7 8 7 0 1 7 2
2 5 9 0 5 5 1 9 6 2 1
3 6 0 1 7 0 1 5 9 0 1
4 7 6 6 5 4 9 0 3 8 0
5 2 6 9 7 4 2 9 5 7 9
6 8 8 4 2 5 0 7 0 8 2
7 7 9 0 8 0 2 0 5 8 1
8 7 1 3 7 0 2 0 9 9 3
9 2 2 6 1 9 8 6 0 2 6
arr = np.where(np.argsort(df_input, axis=1) < 5 , -1, 1)
df_output = pd.DataFrame(arr, columns=df_input.columns)
print (df_output)
a b c d e f g h i j
0 1 -1 1 1 -1 -1 -1 1 -1 1
1 1 1 1 -1 -1 -1 -1 1 1 -1
2 -1 1 1 1 -1 -1 -1 1 -1 1
3 -1 -1 1 -1 1 1 1 -1 -1 1
4 1 1 1 -1 -1 -1 -1 -1 1 1
5 -1 1 -1 1 -1 -1 1 -1 1 1
6 1 1 -1 1 -1 -1 1 -1 -1 1
7 -1 -1 1 1 1 1 -1 -1 1 -1
8 -1 1 -1 1 -1 1 -1 -1 1 1
9 1 -1 -1 -1 1 -1 1 1 1 -1
</code></pre>