[英]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 ![]() |
c ![]() |
|
---|---|---|
0 ![]() |
5 ![]() |
Joanna![]() |
1 ![]() |
19 ![]() |
Jane![]() |
2 ![]() |
4 ![]() |
John![]() |
3 ![]() |
10 ![]() |
Johnna![]() |
4 ![]() |
16 ![]() |
JoJo![]() |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.