Home:ALL Converter>Python - 2 df with same structure add together in 3rd dataframe

Python - 2 df with same structure add together in 3rd dataframe

Ask Time:2021-09-22T05:13:16         Author:jeffrey maier

Json Formatter

I'm just messing around with some football data and I essentially want to add 2 dataframes together on a couple columns.

Here's what I have:

import pandas as pd

d1 = {'PlayerID': [1, 2], 'Name': ['Tyreek', 'Amari'], 'Targets': [15, 16], 'Receptions': [11, 13]}
df1 = pd.DataFrame(data=d1)

d2 = {'PlayerID': [1, 2], 'Name': ['Tyreek', 'Amari'], 'Targets': [4, 5], 'Receptions': [3,3]}
df2 = pd.DataFrame(data=d2)

desired output
[    1   |Tyreek|  19 | 14]
[    2   |Amari |  21 | 16]

Both dataframes have the same columns but are from different weeks of the season. I've tried merge/concat/add but that just adds weeks separately. I would like to create a season to date dataframe that just adds the latest week. For example Tyreek Hill had 15 targets in week one and 4 targets in week 2, so the season to date dataframe should show 19 targets.

Author:jeffrey maier,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69275616/python-2-df-with-same-structure-add-together-in-3rd-dataframe