sherek_66
sherek_66

Reputation: 531

how to make a nested list based on 2 columns?

I have a data frame. I wanna make a nested list of a column based another column.

col1      col2
As     K
SD     k
JK     K
LO     P
WQ     p
IU     A

each element of the nested list is a list of items in col1 that have the same values in col2.

output

Nlist= [[As,SD,JK],[LO,WQ],[A]]

Upvotes: 1

Views: 348

Answers (1)

Celius Stingher
Celius Stingher

Reputation: 18367

I would use a combination of groupby() and .tolist(). However, you would need to first normalize your col2:

df['col2'] = df['col2'].str.lower()
output = df.groupby('col2')['col1'].apply(list).tolist()

This outputs:

[['IU'], ['As', 'SD', 'JK'], ['LO', 'WQ']]

Upvotes: 2

Related Questions