replace blanks in the column with the values in the same column in DF based on the corresponding values in another column in pandas

Question:

Initial table:

| Acc num  | Bank name |
| 100250-- |    NaN    |
| 100250   |    NaN    |
| 100250   |    NaN    |
| 100250   |    SBI    |
| 200100   |    NaN    | 
| 200100   |    NaN    |
| 200100   |   ICICI   |
| 200100   |    NaN    |

Desired output (fill the blanks in the column with the values in the same column in DF based on the corresponding values in another column in pandas):

| Acc num  | Bank name |
| 100250-- |    SBI    |
| 100250   |    SBI    |
| 100250   |    SBI    |
| 100250   |    SBI    |
| 200100   |   ICICI   | 
| 200100   |   ICICI   |
| 200100   |   ICICI   |
| 200100   |   ICICI   |
Asked By: Pythonguy

||

Answers:

You can use groupby on df on column Acc num, and then use bfill and ffill to fill the blank values with values above and below:

df['Bank name'] = df.groupby('Acc num')['Bank name'].bfill().ffill()

Output:

| Acc num  | Bank name |
| 100250   |    SBI    |
| 100250   |    SBI    |
| 100250   |    SBI    |
| 100250   |    SBI    |
| 200100   |   ICICI   | 
| 200100   |   ICICI   |
| 200100   |   ICICI   |
| 200100   |   ICICI   |
Answered By: Mattravel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.