【发布时间】:2023-03-17 19:25:01
【问题描述】:
我整天都在尝试这个,所以我真的希望有人能帮助我。
我有一个看起来像这样的数据框(对不起格式,它不允许我将其格式化为表格,因为它随后指出我的代码中会有错误...):
| ColumnA | ColumnB |otherColumn |
| -------- | ------- |-------------- |
| 1 | n.a. |row x |
| 1 | n.a. |row b |
| 1 | n.a. |row x |
| 2 | 23467 |row x |
| 2 | n.a. |row y |
| 3 | n.a. |row x |
| 3 | 768345 |row y |
| 3 | n.a. |row y |
| 3 | 768345 |row x |
| 4 | 95634511|row x |
| 4 | n.a. |row r |
| 5 | n.a. |row d |
我现在需要在 ColumnA 中具有相同编号的那些行中填充相同的 ColumnB 值。 (在这种情况下不需要 otherColumn,我刚刚添加它以表明还有多个其他列)。如果 ColumnB 中属于 ColumnA 中相同数字的任何行中没有值,则它应保持为 n.a。 (例如“1”和“5”)所以期望的输出应该是
| ColumnA | ColumnB |otherColumn |
| -------- | --------|-------------- |
| 1 | n.a. |row x |
| 1 | n.a. |row b |
| 1 | n.a. |row x |
| 2 | 23467 |row x |
| 2 | 23467 |row y |
| 3 | 768345 |row x |
| 3 | 768345 |row y |
| 3 | 768345 |row y |
| 3 | 768345 |row x |
| 4 | 95634511|row x |
| 4 | 95634511|row r |
| 5 | n.a. |row d |
我尝试将两列转换为字典,但无法分别使用键和值(构建 if 语句);我已经尝试过生成由 ColumnA 和 ColumnB 组成的第二个数据框并尝试合并它(但随后它添加了更多行);我用 update() 和 combine_first() 试过了,也没有成功。
非常感谢每一个建议!
【问题讨论】: