【问题标题】:Put same keys from a column in a list将同一列中的相同键放入列表中
【发布时间】:2020-12-01 14:39:16
【问题描述】:
          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]

我很抱歉解释不好,我第一次使用这个论坛,我的英语不是很好。

【问题讨论】:

  • 能否以预期的输出为例
  • 名称地址 47 Mathilde_AStraat77 AStraat77 AStraat77 与 Bel_BStraat20 和 Berry_AStraat32 一起,因此 Astraat77 的预期列表是 [Mathilde_AStraat77,Bel_Bstraat20, Berry_AStraat32]
  • AStraat77 与 Bel_Bstraat20 和 Berry_AStraat32 在一起,因此 Astraat77 的预期列表是 [Mathilde_AStraat77,Bel_Bstraat20, Berry_AStraat32]
  • 以良好的格式发布代码并编辑您的帖子而不是评论!
  • 对不起,这是我第一次使用这个论坛

标签: python pandas list dataframe key


【解决方案1】:

如果我很清楚你需要什么,它将是以下方式:

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) 返回一个带有重复值的布尔掩码,用于检索在同一列上重复的行。然后访问您想要的列,即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)

【讨论】:

  • 对不起克里斯蒂安,这不是我需要的。谢谢你的努力。我改变了我的描述
  • 我更新了代码。检查是否正常。我获得了与您作为示例相同的输出。
  • 您的输出是一个列表,每道菜都有所有参与者,但我需要这样的列表:` Math_Astraat77 [Math_Astraat77, Berry_AStraat32, Bel_Bstraat20] ` 这个列表包含 Math_Astraat77 在活动中看到的所有人。
  • 抱歉,我看不出有什么不同。如果您选择列表中的一个人,并检查该人是否存在于其他列表中,您将遇到这些人。 'Bel_BStraat20' 锯 [---'Bel_BStraat20'---、'Berry_AStraat32'、'Math_AStraat77'] + ['Aline_AStraat29'、---'Bel_BStraat20'---]、'Berry_AStraat32' 锯 ['Bel_BStraat20'、- --'Berry_AStraat32'---, 'Math_AStraat77'], 'Math_AStraat77' 锯 ['Bel_BStraat20', 'Berry_AStraat32', ---'Math_AStraat77'---], 'Aline_AStraat29' 锯 [---'Aline_AStraat29'- --, 'Bel_Bstraat20'].
猜你喜欢
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多