简体   繁体   English

使用 loc pandas dataframe 追加列

[英]Appending columns using loc pandas dataframe

I am working with a dataframe that I have created with the below code:我正在使用使用以下代码创建的 dataframe:

df = pd.DataFrame({'player': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], 
               'playerlookup': ['B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], 
               'score': ['10', '9', '8', '7', '6', '5', '4', '3']})

I want to add a new column called "scorelookup" to this dataframe that for each row, takes the value in the 'playerlookup' column, searches for it in the 'player' column and then returns the score in a new column.我想在这个 dataframe 中添加一个名为“scorelookup”的新列,对于每一行,在“playerlookup”列中获取值,在“player”列中搜索它,然后在新列中返回分数。 For example, the value in the "scorelookup" column in the first row of the dataframe would be '9' because that was the score for player 'B'.例如,dataframe 第一行的“scorelookup”列中的值为“9”,因为这是玩家“B”的得分。 In instances where the value in the 'playerlookup' column isn't contained within the 'player' column (for example the last row of the table which has a value of 'I' in the 'playerlookup' column), the value in that column would be blank.在“playerlookup”列中的值不包含在“player”列中的情况下(例如,表的最后一行在“playerlookup”列中的值为“I”),该值列将是空白的。

I have tried using code like:我尝试过使用如下代码:

df['playerlookup'].apply(lambda n: df.loc[df['player'] == n, 'score'])

but have been unsuccessful.但一直没有成功。

Any help massively appreciated!任何帮助都非常感谢!

I hope this is the result you are looking for:我希望这是您正在寻找的结果:

import pandas as pd
df = pd.DataFrame({'player': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], 
               'playerlookup': ['B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], 
               'score': ['10', '9', '8', '7', '6', '5', '4', '3']})

d1 = df[["playerlookup"]].copy()
d2 = df[["player","score"]].copy()
d1.rename({'playerlookup':'player'}, axis='columns',inplace=True)

df["scorelookup"] = d1.merge(d2, on='player', how='left')["score"]

The output output

  player  playerlookup  score   scorelookup
0   A          B          10        9
1   B          C           9        8
2   C          D           8        7
3   D          E           7        6
4   E          F           6        5
5   F          G           5        4
6   G          H           4        3
7   H          I           3       NaN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM