我有一个巨大的数据框,仅包含数字(下面显示的数据框仅用于演示目的)。我的目标是替换数据帧的每一行中的第一行n
大于某个值的数字val
by 0.
举个例子:
我的数据框可能如下所示:
c1 c2 c3 c4
0 38 10 1 8
1 44 12 17 46
2 13 6 2 7
3 9 16 13 26
如果我现在选择n = 2
(替换数量)和val = 10
,我想要的输出将如下所示:
c1 c2 c3 c4
0 0 10 1 8
1 0 0 17 46
2 0 6 2 7
3 9 0 0 26
在第一行中,只有一个值大于val
所以只有一个被替换,在第二行中所有值都大于val
但只能替换前两个。第 3 行和第 4 行的模拟(请注意,不仅前两列受到影响,而且一行中的前两个值可以位于任何列中)。
一个简单且非常丑陋的实现可能如下所示:
import numpy as np
import pandas as pd
np.random.seed(1)
col1 = [np.random.randint(1, 50) for ti in xrange(4)]
col2 = [np.random.randint(1, 50) for ti in xrange(4)]
col3 = [np.random.randint(1, 50) for ti in xrange(4)]
col4 = [np.random.randint(1, 50) for ti in xrange(4)]
df = pd.DataFrame({'c1': col1, 'c2': col2, 'c3': col3, 'c4': col4})
val = 10
n = 2
for ind, row in df.iterrows():
# number of replacements
re = 0
for indi, vali in enumerate(row):
if vali > val:
df.iloc[ind, indi] = 0
re += 1
if re == n:
break
这是可行的,但我确信有更有效的方法可以做到这一点。有任何想法吗?