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

后端 未结 3 1876
误落风尘
误落风尘 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:08

    In case you'd like a more expressive way of getting the zero-column names so you can print / log them, and drop them, in-place, by their names:

    zero_cols = [ col for col, is_zero in ((df == 0).sum() == df.shape[0]).items() if is_zero ]
    df.drop(zero_cols, axis=1, inplace=True)
    

    Some break down:

    # a pandas Series with {col: is_zero} items
    # is_zero is True when the number of zero items in that column == num_all_rows
    (df == 0).sum() == df.shape[0])
    
    # a list comprehension of zero_col_names is built from the_series
    [ col for col, is_zero in the_series.items() if is_zero ]
    

提交回复
热议问题