1

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?

user7288808
  • 117
  • 2
  • 8

2 Answers2

4
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']]
ch33hau
  • 2,811
  • 1
  • 15
  • 15
1
[x['B'].values.tolist() for _,x in df.groupby('A')]

Output

[['a', 'b', 'c'], ['d', 'e', 'f']]
iamchoosinganame
  • 1,090
  • 6
  • 15