2

Can't figure out how to drop NaN values from specific column according to another column specific value. Part of DataFrame(df):

            vol.            group
1186      10,448,898          1
1187      nan                 0
1188      35,047,520          1
          ...   
8329      130,703             0
8330      241,489             1
8332      nan                 1
8333      101,142             0
8334      nan                 1

I need to drop nan values from vol. but only when according value in group is 1.

I tried:

df.loc[df['group'] == 1,'vol.'].dropna(inplace=True)

But df still have all values as dropna takes no effect.

unkind58
  • 117
  • 2
  • 11

2 Answers2

3

You can change logic - select all values without 1 with nans in boolean indexing:

#if necessary convert strings nan to missing values `NaN`s
df['vol.'] = df['vol.'].replace('nan', np.nan)


df = df[(df['group'] != 1) | df['vol.'].notna()]
print (df)
            vol.  group
1186  10,448,898      1
1187         NaN      0
1188  35,047,520      1
8329     130,703      0
8330     241,489      1
8333     101,142      0
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
-1

use this:

df = df.loc[df['group'] == 1,'vol.']
df.dropna(inplace=True)
isados
  • 73
  • 2
  • 8
  • 5
    While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained. – Amit Verma Jan 26 '21 at 12:08