从元组A和B(两列)寻找传递关系

2024-06-10 01:12:24 发布

您现在位置:Python中文网/ 问答频道 /正文

现在,你好,我想展示的是喜欢的欺骗性。第一栏的人可能喜欢第二栏的人。基本上,最好有4列A、B、C、d,为每个人显示他们喜欢的人,为那个人显示下一个,等等,基本上从(A、B)元组到(A、B)、(B、C)、(C、d)。 我只知道它必须是递归的,但我不知道如何签入不同的列并以递归的方式检查它们。所以多人可以喜欢一个人,但不是每个人都必须喜欢一个人。但如果是这样的话,它只能发生在3个人身上

所以,我有一个这样的数据帧:

import pandas as pd

d = {'col1': ['Ben', 'Mike', 'Carla', 'Maggy', 'Josh', 'Kai', 'Maria', 'Sophie'], 'col2': ['Carla', 'Carla', 'Josh', 'Ben', 'Lena', 'Maggy', 'Mike', 'Chad']}
df = pd.DataFrame(data=d)
df

我想要这样的输出:

d = {'A': ['Ben', 'Mike', 'Carla', 'Maggy', 'Josh', 'Kai', 'Maria', 'Sophie'], 'B': ['Carla', 'Carla', 'Josh', 'Ben', 'Lena', 'Maggy', 'Mike', 'Chad'], 'C': ['Josh', 'Josh', 'Lena', 'NA', 'NA', 'Ben', 'Carla', 'NA'], 'D': ['Lena', 'Lena', 'NA', 'NA', 'NA', 'NA', 'Josh', 'NA']}
df = pd.DataFrame(data=d)
df

我认为规则是这样的:

  1. 某人(B栏)可以被某人(A栏)喜欢,但某人(B栏)不喜欢任何人。(就像查德不喜欢任何人一样)
  2. 一个人只能被一个人喜欢(A->;B->;NA->;NA)
  3. 有人可以喜欢某个人,某个人喜欢另一个人。(A->;B->;C->;NA)
  4. 一个人可以喜欢一个人,一个喜欢别人的人。有人也喜欢有人。(A->;B->;C->;D->;NA)

我怎样才能做到这一点?多谢各位


Tags: gtdataframedfpdmikebennajosh
1条回答
网友
1楼 · 发布于 2024-06-10 01:12:24

您需要的是两个左连接(合并)操作

以下是代码,为了清晰起见,分为几个步骤:

step1 = pd.merge(df, df, left_on="col2", right_on="col1", how = "left")
step1 = step1[["col1_x", "col2_x", "col2_y"]]
step1.columns = ["first", "second", "third"]

step2 = pd.merge(step1, df, left_on="third", right_on= "col1", how = "left")
res = step2.drop("col1", axis=1).rename(columns={"col2": "fourth"})
print(res) 

结果是:

    first second  third fourth
0     Ben  Carla   Josh   Lena
1    Mike  Carla   Josh   Lena
2   Carla   Josh   Lena    NaN
3   Maggy    Ben  Carla   Josh
4    Josh   Lena    NaN    NaN
5     Kai  Maggy    Ben  Carla
6   Maria   Mike  Carla   Josh
7  Sophie   Chad    NaN    NaN

相关问题 更多 >