Google News
logo
Pandas - Interview Questions
Explain bfill and ffill.
While reindexing NaN can be introduced .bfill and .ffill are used to handle NaN
 
bfill : Fills the value from ahead value into the previous NaN value
ffill  :  Fills the value from behind value into the missing NaN value

Reindexing without using any method(bfill or ffill)
 
import pandas as pd
import numpy as np

df1 = pd.DataFrame(np.random.randn(4, 3), columns=['col1', 'col2', 'col3'])
df2 = pd.DataFrame(np.random.randn(2, 3), columns=['col1', 'col2', 'col3'])

print(df2.reindex_like(df1))

 

Output :

            col1             col2               col3

0    -0.641715     1.031070     -0.208415

1    -1.560385    -0.584403      0.291666

2          NaN           NaN               NaN

3          NaN           NaN               NaN

 

Reindexing with using methods(bfill or ffill)

import pandas as pd
import numpy as np

df1 = pd.DataFrame(np.random.randn(4, 3), columns=['col1', 'col2', 'col3'])
df2 = pd.DataFrame(np.random.randn(2, 3), columns=['col1', 'col2', 'col3'])

print(df2.reindex_like(df1, method='ffill'))


Output :

                  col1               col2               col3

0        1.332612      -0.479218       -1.016999
1       -1.091319     -0.844934       -0.492755
2       -1.091319     -0.844934       -0.492755
3       -1.091319     -0.844934       -0.492755

 

import pandas as pd
import numpy as np

df1 = pd.DataFrame(np.random.randn(4, 3), columns=['col1', 'col2', 'col3'])
df2 = pd.DataFrame(np.random.randn(2, 3), columns=['col1', 'col2', 'col3'])

print(df2.reindex_like(df1, method='bfill'))

 

Output :

                     col1               col2              col3

0           0.526663      -0.450748        0.791112
1          -1.805287       0.641050        1.864871
2                 NaN                 NaN                NaN
3                 NaN                 NaN                NaN

 
 
Advertisement