现在您好,我想显示喜欢的等级制度。第1列中的人可以喜欢第2列中的某人。基本上,最好有4列A,B,C,D列,这些列分别向他们喜欢的每个人和该人显示下一个,等等。基本上从(a,b )元组到(a,b),(b,c),(c,d)。我只知道它必须是递归的,但是例如,我不知道如何才能在Pandas的不同列中检入并以递归的方式检查它们。因此,多个人可以喜欢某人,但并非每个人都必须喜欢某人。但是,如果真是这样,最多只能发生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
我认为规则是这样的:
我该如何实现?谢谢
您需要执行几个左联接(合并)操作。
这里是代码,为了清楚起见,分为几个步骤:
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