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 |
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 |
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 |
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 |