Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge rows with same index on a single data frame?

Tags:

python

pandas

I have a dataframe that looks like this:

A          B           C
1          1234        Win
1          2345        Win
2          1987        Loss
3          3456        Win
3          4567        Win

And I want this to become:

A          B           C
1          1234,2345   Win
2          1987        Loss
3          3456,4567   Win

Note: C values always have the same value for the same index.

Anyone can help? Thanks!

like image 701
ChiefsCreation Avatar asked Oct 29 '15 20:10

ChiefsCreation


People also ask

How do I merge DataFrames with the same index?

concat() to Merge Two DataFrames by Index. You can concatenate two DataFrames by using pandas. concat() method by setting axis=1 , and by default, pd. concat is a row-wise outer join.

How do I combine rows in a data frame?

The concat() function can be used to concatenate two Dataframes by adding the rows of one to the other. The merge() function is equivalent to the SQL JOIN clause. 'left', 'right' and 'inner' joins are all possible.

Can you merge DataFrame on index?

Merging Dataframes by index of both the dataframes As both the dataframe contains similar IDs on the index. So, to merge the dataframe on indices pass the left_index & right_index arguments as True i.e. Both the dataframes are merged on index using default Inner Join.


1 Answers

You can groupby on 'A' and 'C' seeing as their relationship is the same, cast the 'B' column to str and join with a comma:

In [23]:
df.groupby(['A','C'])['B'].apply(lambda x: ','.join(x.astype(str))).reset_index()

Out[23]:
   A     C          B
0  1   Win  1234,2345
1  2  Loss       1987
2  3   Win  3456,4567
like image 153
EdChum Avatar answered Oct 22 '22 21:10

EdChum