I'm pretty new to Pandas and Python, and I simply cannot figure out how to do something that is very easily done in Excel. I was hoping to get a bit of help from the community.
Assume I have the following, which is a df relating to fantasy football that has three columns - 'Name', 'Year', and 'FantasyPts'. Code below.
import pandas as pd
df = pd.DataFrame({'Name': ['Tom Brady', 'Tom Brady', 'Tom Brady', 'Patrick Mahomes', 'Patrick Mahomes', 'Patrick Mahomes'],
'Year': [2019, 2018, 2017, 2019, 2018, 2017],
'FantasyPts': [300, 350, 400, 500, 400, 50],
})
I want to add another column to the table called 'FantasyPtsPreviousYear' but am having a ton of difficulty figuring out how to do so in Pandas / Python.
What I want to do is:
- For each row in the table, have python / pandas check the name and year in that row of the df.
- Look up the fantasy points scored by the same player in the previous year (i.e., Year - 1)
- Populate that number in a new row of the df called 'FantasyPtsPreviousYear' or, if there is no data for the previous year for that player, enter 0.
In Excel, I would simply create new columns and use those columns with VLOOKUPs. The closest thing I have been able to find to VLOOKUP in Pandas is merge but that doesn't seem to work here (or at least I can't figure out how to make it work with this specific application). After trying to find the answer, I think it might have something to do with the loc() function and a For loop, but I can't get it to work.
Thanks for any help you can provide! I greatly appreciate it and think this community is awesome for all of the assistance it provides!