user7288808
user7288808

Reputation: 137

Pandas group a column by another column

I have a pandas dataframe that looks like:

A B
1 a
1 b
1 c
2 d
2 e
2 f

I want to get a list of values for column 'B' by column 'A', so the final product would look like:

list_one = [a, b, c]
list_two = [d, e, f]

I've tried:

df.groupby(['A','B'])

But, this doesn't do what I want it to do.

What would be an elegant pythonic way to achieve this?

Upvotes: 2

Views: 7517

Answers (2)

iamchoosinganame
iamchoosinganame

Reputation: 1120

[x['B'].values.tolist() for _,x in df.groupby('A')]

Output

[['a', 'b', 'c'], ['d', 'e', 'f']]

Upvotes: 1

ch33hau
ch33hau

Reputation: 2971

import pandas as pd

df = pd.DataFrame([
    {'A':1, 'B': 'a'},
    {'A':1, 'B': 'b'},
    {'A':1, 'B': 'c'},
    {'A':2, 'B': 'd'},
    {'A':2, 'B': 'e'},
    {'A':2, 'B': 'f'}])

list(df.groupby('A')['B'].apply(list).values)

# Output
# [['a', 'b', 'c'], ['d', 'e', 'f']]

Upvotes: 5

Related Questions