-1

I have a dataframe currently which resembles this

Source | Destination | Type
A | B | Insert
A | B | Delete
B | C | Insert

What I want to achieve is something like this

Source | Destination | Type
A | B | Insert, Delete
B | C | Insert

I tried using group by Source and Destination but Im a little unsure how do I append to the type. Any ideas?

Adam
  • 1,157
  • 6
  • 19
  • 40
  • Does this answer your question? [How to combine multiple rows into a single row with pandas](https://stackoverflow.com/questions/36392735/how-to-combine-multiple-rows-into-a-single-row-with-pandas) – Vladimir Fokow Aug 14 '22 at 14:08

4 Answers4

0

Check Below Code:

df.groupby(['Source','Destination']).agg({'Type':'unique'})
Abhishek
  • 1,585
  • 2
  • 12
  • 15
0

Figured out something

df = df.groupby(['Source','Destination'])['Type'].apply(lambda x: ','.join(x)).reset_index()
Adam
  • 1,157
  • 6
  • 19
  • 40
0

Make a string separated by ", ":

df.groupby(['Source', 'Destination']).agg(', '.join).reset_index()

Make a list:

df.groupby(['Source','Destination']).agg(list).reset_index()
Vladimir Fokow
  • 3,728
  • 2
  • 5
  • 27
0

Joining by , and building a string works but it is not very convenient if you later want to perform other operations with this column value. (such as iterating over the elements.)

This creates a set of values.

column_map: Dict[str,Any] = {} column_map["Type"] = lambda x: set(x)

df.groupby(["Source", "Destination"]).agg(column_map)

Source | Destination | Type
A | B | {Insert Delete}
B | C | {Insert}

if you instead want to get a list and dont want eliminate duplicates. Just replace set(x) with list(x)

Berkay Berabi
  • 1,933
  • 1
  • 10
  • 26