如标题中所述,如何基于列列表将列转换为0。我需要将列表中的前3列匹配为1后,将任何列转换为0。

例如

list1 = [“ a”,“ c”,“ d”,“ e”,“ b”]

df =

    a   b   c   d   e
0   1   1   0   1   1
1   0   0   0   1   1
2   0   0   0   0   0
3   1   1   1   0   0
4   0   0   0   0   0
5   1   1   1   1   1


我想要的是:

    a   b   c   d   e
0   1   0   0   1   1
1   0   0   0   1   1
2   0   0   0   0   0
3   1   1   1   0   0
4   0   0   0   0   0
5   1   0   1   1   0


目前,我正在逐行浏览每个列表。随着此数据帧变大,它将花费的时间越来越长,所以我想看看是否有一种有效的方法来做到这一点。

我当前的代码是:

a=np.random.randint(2, size=(6, 5))
df=pd.DataFrame(a,columns=["a","b",'c','d',"e"])
filterlist=["a","c",'d','e','b']

%%timeit
counter=1
for eachindex in df.index:
    for item in filterlist:
        if  (df.iloc[eachindex][item])==1:
            counter=counter+1
            if counter>4:
                df.loc[eachindex,item]=0
    counter=1


时间是:

2.7 ms ± 60.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

最佳答案

您可以使用reindexcumsum,然后使用mask返回

df.mask(df.reindex(columns=filterlist).cumsum(1).gt(3),0)
Out[620]:
   a  b  c  d  e
0  1  0  0  1  1
1  0  0  0  1  1
2  0  0  0  0  0
3  1  1  1  0  0
4  0  0  0  0  0
5  1  0  1  1  0

10-08 02:22