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!
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With