使用pandas根据另一列中的相应值,将列中的空白替换为DF中相同列中的值。

huangapple go评论65阅读模式
英文:

replace 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-- |    NaN    |
| 100250   |    NaN    |
| 100250   |    NaN    |
| 100250   |    SBI    |
| 200100   |    NaN    | 
| 200100   |    NaN    |
| 200100   |   ICICI   |
| 200100   |    NaN    |

期望输出(根据pandas中另一列的相应值填充列中的空白值):

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

答案1

得分: 0

你可以在dfAcc num列上使用groupby,然后使用bfillffill来填充空白值,将它们填充为上方和下方的数值:

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

输出结果:

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

huangapple
  • 本文由 发表于 2023年3月1日 10:24:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75599050.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定