I have two pandas DataFrames containing differently ordered data, and I am trying to move data from one to the other based on content. I've tried a lambda function, but I don't think I'm understanding how this is supposed to work. Here are simplified versions of my data:
df1 =
Name Pos Opponent DPAvPos
1 Dave QB DEN NaN
2 Bill QB GB NaN
3 Sean QB DET NaN
df2 =
Name DKP/Game
1 DET 20.1
2 DEN 10.4
3 GB 15.2
I would like to move data from the DKP/Game column of df2 to the DPAvPos column df1 by matching data from the Opponent column of df1 with the Name column of df2. So far everything I've tried hasn't worked.
You could try to merge these two dataframes, then drop DPAvPos and rename DKP/Game as DPAvPos :
import pandas as pd
df1 = pd.DataFrame({
"Name" : ["Dave", "Bill", "Sean"],
"Pos" : ['QB', 'QB', 'QB'],
"Opponent" : ["DEN", "GB", "DET"],
"DPAvPos": ["NaN", "NaN", "NaN"]
})
df2 = pd.DataFrame({
"Name" : ["DET", "DEN", "GB"],
"DKP/Game" : [ 20.1, 23, 21]
})
df2.rename(columns={"Name" : "Opponent"}, inplace=True)
df3 = pd.merge(df1, df2, on="Opponent")
df3.drop('DPAvPos', axis=1, inplace=True)
df3.rename(columns={"DKP/Game" : "DPAvPos"}, inplace=True)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.