pandas dataframe drop columns by number of nan

后端 未结 5 824
忘了有多久
忘了有多久 2021-01-04 02:08

I have a dataframe with some columns containing nan. I\'d like to drop those columns with certain number of nan. For example, in the following code, I\'d like to drop any co

5条回答
  •  暖寄归人
    2021-01-04 02:09

    There is a thresh param for dropna, you just need to pass the length of your df - the number of NaN values you want as your threshold:

    In [13]:
    
    dff.dropna(thresh=len(dff) - 2, axis=1)
    Out[13]:
              A         B
    0  0.517199 -0.806304
    1 -0.643074  0.229602
    2  0.656728  0.535155
    3       NaN -0.162345
    4 -0.309663 -0.783539
    5  1.244725 -0.274514
    6 -0.254232       NaN
    7 -1.242430  0.228660
    8 -0.311874 -0.448886
    9 -0.984453 -0.755416
    

    So the above will drop any column that does not meet the criteria of the length of the df (number of rows) - 2 as the number of non-Na values.

提交回复
热议问题