user7330810
user7330810

Reputation:

merge row values in two consecutive rows using pandas

i am using pandas and have a data frame where I would like to merge two of the rows together and append the values in each cell separated by a symbol. The cells contain text or integers.

The original data frame looks like this

index         1         2          3
0           2010      2011       2012
1           First     Second     Third
2            98%        99%        99%
3            77%        87%        77%

I would like to achieve this :

index         1                 2                   3
    0    2010 | First      2011 | Second       2012 | Third
    2        98%               99%                 99%
    3        77%               87%                 77%

What's the best way to achieve this?

Upvotes: 2

Views: 1328

Answers (2)

BENY
BENY

Reputation: 323266

Or maybe you can try this by using T

df=df.T
df[0]=df[0].astype(str)+'|'+df[1]
df.drop(1,1).T


                1            2           3
index                                     
0      2010|First  2011|Second  2012|Third
2             98%          99%         99%
3             77%          87%         77%

Upvotes: 0

Scott Boston
Scott Boston

Reputation: 153460

Let's try this:

df.loc[0] = df[:2].apply(lambda x: ' | '.join(x.astype(str)))
df = df.drop(1).reset_index()
df

Output:

   index             1              2             3
0      0  2010 | First  2011 | Second  2012 | Third
1      2           98%            99%           99%
2      3           77%            87%           77%

Upvotes: 3

Related Questions