Python Pandas Dataframe, remove all rows where 'None' is the value in any column

前端 未结 3 1769
我在风中等你
我在风中等你 2021-02-01 17:02

I have a large dataframe. When it was created \'None\' was used as the value where a number could not be calculated (instead of \'nan\')

How can I delete all rows that h

3条回答
  •  不知归路
    2021-02-01 17:43

    Setup
    Borrowed @MaxU's df

    df = pd.DataFrame([
        [1, 2, 3],
        [4, None, 6],
        [None, 7, 8],
        [9, 10, 11]
    ], dtype=object)
    

    Solution
    You can just use pd.DataFrame.dropna as is

    df.dropna()
    
       0   1   2
    0  1   2   3
    3  9  10  11
    

    Supposing you have None strings like in this df

    df = pd.DataFrame([
        [1, 2, 3],
        [4, 'None', 6],
        ['None', 7, 8],
        [9, 10, 11]
    ], dtype=object)
    

    Then combine dropna with mask

    df.mask(df.eq('None')).dropna()
    
       0   1   2
    0  1   2   3
    3  9  10  11
    

    You can ensure that the entire dataframe is object when you compare with.

    df.mask(df.astype(object).eq('None')).dropna()
    
       0   1   2
    0  1   2   3
    3  9  10  11
    

提交回复
热议问题