Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Merge two rows into a single row based on columns

I have 2 rows that look like these,

------------------------------
DealName | Target | Acquirer |
-----------------------------
ABC-XYZ  | ABC    | None     |
------------------------------
ABC-XYZ  | None   | XYZ      |
------------------------------

I'm looking to merge them into a single as:

------------------------------
DealName | Target | Acquirer |
-----------------------------
ABC-XYZ  | ABC    | XYZ      |
------------------------------

Not sure how to accomplish this in Pandas. Any pointers will be highly appreciated! Thanks in advance

like image 593
Kshitij G Avatar asked Aug 03 '18 13:08

Kshitij G


People also ask

How do I combine multiple rows into one row in Python?

To merge rows within a group together in Pandas we can use the agg(~) method together with the join(~) method to concatenate the row values.

How do I merge two rows in pandas?

merge() for combining data on common columns or indices. . join() for combining data on a key column or an index. concat() for combining DataFrames across rows or columns.

What is the difference between join () and merge () in pandas?

Both join and merge can be used to combines two dataframes but the join method combines two dataframes on the basis of their indexes whereas the merge method is more versatile and allows us to specify columns beside the index to join on for both dataframes.


1 Answers

IIUC

df.replace('None','').groupby('DealName',as_index=False).agg(''.join)
Out[25]: 
  DealName Target Acquirer
0  ABC-XYZ    ABC      XYZ
like image 83
BENY Avatar answered Oct 24 '22 07:10

BENY