11
$\begingroup$

I have a Dataframe, i need to drop the rows which has all the values as NaN.

ID      Age    Gender
601     21       M
501     NaN      F
NaN     NaN      NaN

The resulting data frame should look like.

Id     Age    Gender
601     21      M
501    NaN      F

I used df.drop(axis = 0), this will delete the rows if there is even one NaN value in row. Is there a way to do as required?

$\endgroup$

2 Answers 2

21
$\begingroup$

The complete command is this:

df.dropna(axis = 0, how = 'all', inplace = True)

you must add inplace = True argument, if you want the dataframe to be actually updated. Alternatively, you would have to type:

df = df.dropna(axis = 0, how = 'all')

but that's less pythonic IMHO.

$\endgroup$
5
  • 3
    $\begingroup$ inplace is not recommended and will actually be removed in future versions: github.com/pandas-dev/pandas/issues/16529 $\endgroup$
    – tdy
    Commented Feb 3, 2023 at 22:51
  • $\begingroup$ Good point. Obviously when I wrote this reply the use of inplace was not deprecated. $\endgroup$
    – Leevo
    Commented Feb 25, 2023 at 10:53
  • $\begingroup$ @tdy Interesting that issue was from 2017 and in 2023 inplace has not been deprecated. $\endgroup$
    – mp252
    Commented Nov 22, 2023 at 15:34
  • 1
    $\begingroup$ @mp252 inplace has been inadvisable since 2017, but it won't start being "deprecated" (formally in the API) until the PDEP-8 proposal gets merged. $\endgroup$
    – tdy
    Commented Nov 23, 2023 at 1:41
  • $\begingroup$ Good to know! Looks like I have got a lot of refactoring to do! $\endgroup$
    – mp252
    Commented Nov 23, 2023 at 15:55
2
$\begingroup$

This should do it:

df.dropna(axis = 0, how = 'all')
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.