我想用DataFrame2(DF2)中相应的'Salary'填充DataFrame1(DF1)中的'Salary'列。这些需要在“团队”和“球员”上进行匹配。
注意:
数据帧是: 大小不一样。 顺序不一样。
import pandas as pd
#df 1:
nba_data = {'Team': ['Mavericks', 'Mavericks', 'Mavericks', '', 'NewYorkKnicks17','Houston Rockets', 'NewYorkKnicks17'],
'Players': ['Luka Doncic', 'Kristaps Porzingis', 'Jalen Brunson', 'Kristaps Porzingis', 'JR Smith',
'James Harden', 'Derrick Rose',],
'Salary': ['0', '0', '0','0', '0', '0', '0'],
'Coach': ['Rick Carlisle', 'Rick Carlisle', 'Steve Kerr', 'Phil Jackson', 'Tom Thibideou', '', '']}
nba_df1 = pd.DataFrame(nba_data)
nba_df1
#df2:
nba_data2 = {'Team': ['Mavericks', 'Mavericks', 'Mavericks', 'NewYorkKnicks17', 'NewYorkKnicks17', 'NewYorkKnicks17', 'Houston Rockets'],
'Players': ['Luka Doncic', 'Kristaps Porzingis', 'Steph Curry', 'JR Smith', 'Derrick Rose',
'Kristaps Porzingis', 'James Harden'],
'Salary': ['3m', '126m', '0','115m', '0', '20m', '1.5m'],
'Coach': ['Rick Carlisle', 'Rick Carlisle', 'Steve Kerr', '', 'Tom Thibideou', 'Phil Jackson', '']}
nba_df2 = pd.DataFrame(nba_data2)
nba_df2
所需结果= nba_df1,其中填充了适当的薪水(运行以下操作):
nba_data3 = {'Team': ['Mavericks', 'Mavericks', 'Mavericks', '', 'NewYorkKnicks17','Houston Rockets', 'NewYorkKnicks17'],
'Players': ['Luka Doncic', 'Kristaps Porzingis', 'Jalen Brunson', 'Kristaps Porzingis', 'JR Smith',
'James Harden', 'Derrick Rose',],
'Salary': ['3m', '126m', '0','20m', '115m', '1.5m', '0'],
'Coach': ['Rick Carlisle', 'Rick Carlisle', 'Steve Kerr', 'Phil Jackson', 'Tom Thibideou', '', '']}
nba_df1_adjusted = pd.DataFrame(nba_data3)
Kindly note: this is not a tutorial. - it is a specific question and therefore not a duplicate of a general tutorial.
答案 0 :(得分:2)
agg = pd.merge(nba_df1, nba_df2, on = ['Players', 'Team'], how = 'left')
您的结果将在Salary_y上
编辑: 有点脏,但可以用:
agg = pd.merge(nba_df1, nba_df2[['Team', 'Players', 'Salary']], on = ['Players', 'Team'], how = 'left')
agg2 = pd.merge(nba_df1, nba_df2, on = ['Players', 'Coach'], how = 'left')
merge = pd.merge(agg, agg2, on = ['Players', 'Coach'])
merge['Salary'] = merge['Salary_y_x'].fillna(merge['Salary_y_y'])