简体   繁体   English

Pandas:基于其他两列值的新列

[英]Pandas: New column based on values of two other columns

I have two columns one with OLD id number that (column b) and another column with the NEW id number (a).我有两列,一列带有旧 ID 号(b 列),另一列带有新 ID 号(a)。 I want to find out what name (c) corresponded to the old id number given the information I have in a and c.鉴于我在 a 和 c 中的信息,我想找出与旧 ID 号对应的名称 (c)。

# Example dataset
print(df1)

# output
a  b  c
4  5  John
5  19 Joanna
1  4  Jenna
19 10 Jane
10 66 Johnna
16 16 JoJo

What I am trying to achieve:我想要达到的目标:

print(df2)

# output
b  d 
5  Joanna
19 Jane
4  John
10 Johnna
66 na
16 JoJo
df['d'] = df['b'].map(dict(df[['a', 'c']].to_numpy()))

It's a self join.这是一个自我加入。

df = pd.read_csv(io.StringIO("""a  b  c
4  5  John
5  19 Joanna
1  4  Jenna
19 10 Jane
10 66 Johnna
16 16 JoJo"""), sep="\s+")

df.merge(df, left_on="b", right_on="a").loc[:,["b_x","c_y"]].rename(columns={"b_x":"b","c_y":"c"})

b b c c
0 0 5 5 Joanna乔安娜
1 1 19 19 Jane
2 2 4 4 John约翰
3 3 10 10 Johnna约翰娜
4 4 16 16 JoJo乔乔

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

相关问题 使用熊猫基于其他两列中的值替换列中的值 - Replace values in column based on values in two other columns using pandas 这个 Numpy/Pandas 代码根据另外两个布尔列中的值构造新的布尔列有什么问题? - What is wrong with this Numpy/Pandas code to construct new boolean column based on the values in two other boolean columns? 根据来自其他两列的条件文本值在 Pandas 中创建一个新列 - Create a new column in pandas based on conditional text values from two other columns pandas,根据其他两列的值创建一个新的唯一标识符列 - pandas, create a new unique identifier column based on values from two other columns Pandas DataFrame 基于其他两列创建新的 csv 列 - Pandas DataFrame create new csv column based on two other columns Pandas 根据其他两列的划分创建新列 - Pandas create new column based on division of two other columns 在 pandas 中创建一个基于其他两个布尔列的新列 - Create a new column in pandas that is based on two other columns of bools 基于python pandas中其他列的值创建新列 - Creating a new column based on values from other columns in python pandas 根据其他 pandas 列中列表中的值数创建新列? - Create new columns based on number of values in list in other pandas column? 根据Pandas中其他列的值将值分配给新列 - Assigning value to a new column based on the values of other columns in Pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM