将同一列中的相同键放入列表中

Put same keys from a column in a list

          Name         Adress       Voor        Hoofd         Na     Dish
0   Aisha_BStraat15 BStraat15   BStraat13   BStraat15   AStraat22   Hoofd
1   Aline_AStraat29 AStraat29   AStraat48   AStraat29   AStraat81   Hoofd
2   Alma_BStraat21  BStraat21   AStraat53   BStraat51   BStraat21   Na
9   Bel_BStraat20   BStraat20   AStraat48   BStraat20   AStraat77   Hoofd
10  Berry_AStraat32 AStraat32   BStraat8    AStraat32   AStraat77   Hoofd
47  Math_AStraat77  AStraat77   BStraat58   AStraat57   AStraat77   Na

这是我的数据框的一部分。它正在计划一项活动,其中包含三道名为 Voor、Hoofd 和 Na 的菜肴。每个地址准备一道菜,在最后一个格子里看。在同名 Voor Hoofd 和 Na 的单元格中,您会看到人们必须吃这道菜的地址。

我想为列表中的每个名字制作一个列表,名字在活动中遇到的名字,例如:Math_Astraat77 在活动中遇到了 Berry_AStraat32 和 Bel_BStraat20。

可能的输出:

[Math_Astraat77, Berry_AStraat32, Bel_BStraat20]

对于不好的解释我深表歉意,我第一次使用这个论坛并且我的英语不是很好atm。

如果我很了解你需要什么,将通过以下方式:

voor_values = list(df[df.Voor.duplicated(keep=False)].Name.values)
hoofd_values = list(df[df.Hoofd.duplicated(keep=False)].Name.values)
na_values = list(df[df.Na.duplicated(keep=False)].Name.values)

repeated_values = voor_values + hoofd_values + na_values

属性 duplicated(keep=False) return 具有重复值的布尔掩码,用于检索在同一列上重复的行。然后访问所需的列,即 Name,并使用 values 属性.

获取数组中的元素

如果前面的想法是正确的你可以归纳如下:

column_names = ['Voor', 'Hoofd', 'Na']
repeated_values = []
for col_name in column_names:
   repeated_values.append(list(df[df[col_name].duplicated(keep=False)].Name.values))

repeated_values 将有一个包含名称的列表。

for col, names in zip(column_names, repeated_values):
    print(col, names)