[英]How to move data from one dataframe to another based on matching column values with pandas?
I have two pandas DataFrames containing differently ordered data, and I am trying to move data from one to the other based on content. 我有两个pandas DataFrames,它们包含顺序不同的数据,并且我正在尝试根据内容将数据从一个移到另一个。 I've tried a lambda function, but I don't think I'm understanding how this is supposed to work.
我已经尝试过lambda函数,但是我认为我不了解这应该如何工作。 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. 我想通过将df1的Opponent列中的数据与df2的Name列进行匹配,将数据从df2的DKP / Game列移动到DPAvPos列df1。 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 : 您可以尝试合并这两个数据帧,然后删除DPAvPos并将DKP / Game重命名为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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.