0
          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

This is a part of my dataframe. It is planning of an event with three dishes named Voor, Hoofd and Na. Every adress prepare one dish, see it in the last cell. In the cells with collnames Voor Hoofd and Na you see the adress where people have to eat the dish.

I want to make a list for every Name within the list the Names who the Name met at the event for expamle: Math_Astraat77 met Berry_AStraat32 and Bel_BStraat20 at the event.

Possible output:

[Math_Astraat77, Berry_AStraat32, Bel_BStraat20]

my apologies for the bad explanation, First time i used this forum and my English is not very well atm.

Timo V
  • 119
  • 9
  • 1
    Does this answer your question? [How to group dataframe rows into list in pandas groupby](https://stackoverflow.com/questions/22219004/how-to-group-dataframe-rows-into-list-in-pandas-groupby) – G. Anderson Dec 01 '20 at 16:16
  • @G.Anderson this is WAY more easier than i thought it would be :p – ombk Dec 01 '20 at 16:24
  • Haha, I find that is often the case with pandas. If you want to do something with a dataframe, there is _almost always_ a convenient method already created to do whatever you need – G. Anderson Dec 01 '20 at 17:12

1 Answers1

1

Apparently df.groupby("Na")["Name"].agg(list) works as well and it is way less work. (it's all about learning).

df.groupby("Na")["Name"].agg([",".join])["join"].apply(lambda x: x.split(","))

#output

Na
AStraat22                                   [Aisha_BStraat15]
AStraat77    [Bel_BStraat20, Berry_AStraat32, Math_AStraat77]
AStraat81                                   [Aline_AStraat29]
BStraat21                                    [Alma_BStraat21]
Name: join, dtype: object

Is that what you want?

df.groupby("Na")["Name"].agg([",".join])["join"].\
apply(lambda x: x.split(",") if len(x.split(","))>1 else x)

#output

Na
AStraat22                                     Aisha_BStraat15
AStraat77    [Bel_BStraat20, Berry_AStraat32, Math_AStraat77]
AStraat81                                     Aline_AStraat29
BStraat21                                      Alma_BStraat21
Name: join, dtype: object

ombk
  • 2,036
  • 1
  • 4
  • 16