python - pandas - 仅更新基于 'key' 值的特定 DataFrame 列值

标签 python pandas dataframe merge updates

我有以下两个数据框,

统计:

player_id   player_name   gp    ab   run   hit
    28920      S. Smith    1     2     1     3
    33351    T. Mancini    0     0     0     0
    30267     C. Gentry    0     0     0     0
    34885        H. Kim    1     0     0     0
    31988     J. Schoop    0     0     0     0
     5908    J.J. Hardy    1     3     0     0

& 游戏:

player_id   player_name   gp    ab   run    hit
    28920      S. Smith    1     4     1      1
    33351    T. Mancini    1     1     0      1
    34885        H. Kim    1     1     2      0
    5908     J.J. Hardy    1     4     0      0

我只想根据 player_id 更新在上一场比赛中活跃的玩家的统计数据,因此最终的统计数据 DataFrame 如下所示:

player_id   player_name   gp    ab   run   hit
    28920      S. Smith    2     6     2     4
    33351    T. Mancini    1     1     0     1
    30267     C. Gentry    0     0     0     0
    34885        H. Kim    2     1     2     0
    31988     J. Schoop    0     0     0     0
     5908    J.J. Hardy    2     7     0     0

感谢您的宝贵时间和帮助!

最佳答案

你可以用 set_indexupdate

stats=stats.set_index(['player_id','player_name'])
game=game.set_index(['player_id','player_name'])
stats.update(game)
stats = stats.astype(int).reset_index()
stats
Out[452]: 
   player_id player_name  gp  ab  run  hit
0      28920     S.Smith   1   4    1    1
1      33351   T.Mancini   1   1    0    1
2      30267    C.Gentry   0   0    0    0
3      34885       H.Kim   1   1    2    0
4      31988    J.Schoop   0   0    0    0
5       5908   J.J.Hardy   1   4    0    0

由于您使用 add

更新了您的问题
#stats=stats.set_index(['player_id','player_name'])
#game=game.set_index(['player_id','player_name'])
stats.add(game,fill_value=0).astype(int).reset_index()
Out[460]: 
   player_id player_name  gp  ab  run  hit
0       5908   J.J.Hardy   2   7    0    0
1      28920     S.Smith   2   6    2    4
2      30267    C.Gentry   0   0    0    0
3      31988    J.Schoop   0   0    0    0
4      33351   T.Mancini   1   1    0    1
5      34885       H.Kim   2   1    2    0

关于python - pandas - 仅更新基于 'key' 值的特定 DataFrame 列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50353592/

相关文章:

python - python strptime的自定义格式指令

python Pandas : How to groupby and count and select a portion of counts?

r - R中具有不同摘要的相同数据帧?

python - 单线程应用程序的连接池

python - 在不安装 Python 的情况下,在 Cloudera 虚拟机上安全地拥有两个版本的 Python

Python 将计数器转换为 DataFrame 列

python - 如何将应用函数链接到 pandas 数据框的子集

python - 如何使用类似分组的函数将值插入新列?

python - 按 25 个 block 对 CSV 中的行进行分组

python - 使用 Pandas 从函数返回多个 DataFrame