Dealing with NaN values

[1]:
import pandas as pd
import numpy as np
from plydata import call
[2]:
df = pd.DataFrame({
    'w': [1, 2, np.nan, 4, 5],
    'x': [np.nan, 2, np.nan, 4, 5],
    'y': [np.nan] * 4 + [5],
    'z': [np.nan] * 5
})
df
[2]:
w x y z
0 1.0 NaN NaN NaN
1 2.0 2.0 NaN NaN
2 NaN NaN NaN NaN
3 4.0 4.0 NaN NaN
4 5.0 5.0 5.0 NaN

Drop NaN Values

Drop rows with any NaN values

[3]:
df >> call(pd.DataFrame.dropna)
[3]:
w x y z
[4]:
# You can call method on the dataframe with '.method_name'
df >> call('.dropna')
[4]:
w x y z

Drop rows with all NaN values

[5]:
df >> call('.dropna', how='all')
[5]:
w x y z
0 1.0 NaN NaN NaN
1 2.0 2.0 NaN NaN
3 4.0 4.0 NaN NaN
4 5.0 5.0 5.0 NaN

Drop rows with NaN values in the x column.

[6]:
df >> call('.dropna', subset=['x'])
[6]:
w x y z
1 2.0 2.0 NaN NaN
3 4.0 4.0 NaN NaN
4 5.0 5.0 5.0 NaN

Drop and keep rows atleast 3 non-NaN values

[7]:
df >> call('.dropna', thresh=3)
[7]:
w x y z
4 5.0 5.0 5.0 NaN

Drop columns with all NaN values

[8]:
df >> call('.dropna', axis=1, how='all')
[8]:
w x y
0 1.0 NaN NaN
1 2.0 2.0 NaN
2 NaN NaN NaN
3 4.0 4.0 NaN
4 5.0 5.0 5.0

Drop columns with any NaN values in row 3.

[9]:
df >> call('.dropna', axis=1, subset=[3])
[9]:
w x
0 1.0 NaN
1 2.0 2.0
2 NaN NaN
3 4.0 4.0
4 5.0 5.0

Fill NaN values

Replace all NaN values with -1.

[10]:
df >> call(pd.DataFrame.fillna, -1)
[10]:
w x y z
0 1.0 -1.0 -1.0 -1.0
1 2.0 2.0 -1.0 -1.0
2 -1.0 -1.0 -1.0 -1.0
3 4.0 4.0 -1.0 -1.0
4 5.0 5.0 5.0 -1.0
[11]:
df >> call('.fillna', -1)
[11]:
w x y z
0 1.0 -1.0 -1.0 -1.0
1 2.0 2.0 -1.0 -1.0
2 -1.0 -1.0 -1.0 -1.0
3 4.0 4.0 -1.0 -1.0
4 5.0 5.0 5.0 -1.0

Replace all NaN values with the first non-NaN value above in column

[12]:
df >> call('.fillna', method='ffill')
[12]:
w x y z
0 1.0 NaN NaN NaN
1 2.0 2.0 NaN NaN
2 2.0 2.0 NaN NaN
3 4.0 4.0 NaN NaN
4 5.0 5.0 5.0 NaN

Replace all NaN values with the first non-NaN value below in column

[13]:
df >> call('.fillna', method='bfill')
[13]:
w x y z
0 1.0 2.0 5.0 NaN
1 2.0 2.0 5.0 NaN
2 4.0 4.0 5.0 NaN
3 4.0 4.0 5.0 NaN
4 5.0 5.0 5.0 NaN

Replace atmost 2 NaN values with the first non-NaN value below in column

[14]:
df >> call('.fillna', method='bfill', limit=2)
[14]:
w x y z
0 1.0 2.0 NaN NaN
1 2.0 2.0 NaN NaN
2 4.0 4.0 5.0 NaN
3 4.0 4.0 5.0 NaN
4 5.0 5.0 5.0 NaN

Replace all NaN values with the first non-NaN value to the left in the row

[15]:
df >> call('.fillna', method='ffill', axis=1)
[15]:
w x y z
0 1.0 1.0 1.0 1.0
1 2.0 2.0 2.0 2.0
2 NaN NaN NaN NaN
3 4.0 4.0 4.0 4.0
4 5.0 5.0 5.0 5.0

Replace all NaN values with the first non-NaN value to the right in the row

[16]:
df >> call('.fillna', method='bfill', axis=1)
[16]:
w x y z
0 1.0 NaN NaN NaN
1 2.0 2.0 NaN NaN
2 NaN NaN NaN NaN
3 4.0 4.0 NaN NaN
4 5.0 5.0 5.0 NaN