How do I delete a column that contains only zeros in Pandas?

后端 未结 3 1878
误落风尘
误落风尘 2020-12-07 09:06

I currently have a dataframe consisting of columns with 1\'s and 0\'s as values, I would like to iterate through the columns and delete the ones that are made up of only 0\'

3条回答
  •  感动是毒
    2020-12-07 09:16

    Here is an alternative way to use is

    df.replace(0,np.nan).dropna(axis=1,how="all")

    Compared with the solution of unutbu, this way is obviously slower:

    %timeit df.loc[:, (df != 0).any(axis=0)]
    652 µs ± 5.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    
    %timeit df.replace(0,np.nan).dropna(axis=1,how="all")
    1.75 ms ± 9.49 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    

提交回复
热议问题