从另一个Dataframe中查找ID和值

时间:2018-04-02 03:11:24

标签: python pandas

假设我们有两个数据帧(Baseball_ID和Baseball_Games),我们如何向Baseball_Games添加两列(Home_City和Away_City)并包含全部名称" City" (例如波士顿,马萨诸塞州)来自Baseball_ID的每支球队?

Baseball_ID:

  Team_ID    City     
  BOS        Boston, MA   
  DET        Detroit, MI
  NYY        New York, NY
  PIT        Pittsburgh, PA

Baseball_Games:

  Home      Away    Home_City    Away_City 
  NYY       DET     ??           ??
  PIT       BOS     ??           ??

1 个答案:

答案 0 :(得分:0)

我认为你正在寻找'合并'功能:

Baseball_Games = pd.merge(Baseball_Games, Baseball_id, how='inner', left_on='Home', 
  right_on='Team_ID').drop('Team_ID', axis=1).rename(columns={'City': 'Home_City'})
Baseball_Games = pd.merge(Baseball_Games, Baseball_id, how='inner', left_on='Away', 
  right_on='Team_ID').drop('Team_ID', axis=1).rename(columns={'City': 'Away_City'})

结果:

    Home    Away Home_City      Away_City
0   NYY     DET  New York, NY   Detroit, MI
1   PIT     BOS  Pittsburgh, PA Boston, MA

从您的问题中不确定任何列是否为索引。如果是,请使用'right_index'= True(或'left_index',无论您需要哪个数据框的索引),而不是'right_on'或'left_on'。

希望这有帮助