Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PYTHON (PANDAS) Concatenate content of two rows on the last of these two rows

I’m struggling on concatenations of content of two rows into the last of these two rows.

Here my situation:

A B C D
NaN NaN Rossi Brambilla
Federico Giovanni Giorgio Marcello

I would like something like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A B C D
NaN NaN Rossi Brambilla
Federico Giovanni Rossi Giorgio Brambilla Marcello

Could you please help me to reach this result?

Thanks in advance!

I tried the following:

df.iloc[1] = df_bo.iloc[0] + " " + df_bo.iloc[1]

but it gives me the following

IndexError: single positional indexer is out-of-bounds

I tried to transpose DF too, but it’s seems to be a bit sophisticated.

>Solution :

You can use stack to get rid of the NaNs, then groupby.agg to join the names:

df.iloc[1] = df.stack().groupby(level=1).agg(' '.join)

If you want to limit the input rows:

df.iloc[1] = df.iloc[:2].stack().groupby(level=1).agg(' '.join)

Output:

          A         B              C                   D
0       NaN       NaN          Rossi           Brambilla
1  Federico  Giovanni  Rossi Giorgio  Brambilla Marcello
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading