-2

For example the below dataframes I have 4 rows

A    B    C
a    b    c
D    E    F
d    e    f

i would like to append row 3 to row 1, and row 4 to row 2 to form a six-column row, i.e.

A    B    C    D    E    F
a    b    c    d    e    f

How to achieve it in pandas?

1 Answers1

1

UPDATE:

Source DF:

In [47]: df
Out[47]:
   0  1  2
0  A  B  C
1  a  b  c
2  D  E  F
3  d  e  f

Solution:

In [46]: pd.DataFrame(np.stack([df.iloc[::2].values.ravel(),
                                df.iloc[1::2].values.ravel()])) \
           .add_prefix('col')
Out[46]:
  col0 col1 col2 col3 col4 col5
0    A    B    C    D    E    F
1    a    b    c    d    e    f

Old answer: for the original answer, which was changed...

IIUC:

In [23]: pd.DataFrame(df.values.reshape(1,-1), columns=np.arange(1, df.size+1)) \
           .add_prefix('col')
Out[23]:
  col1 col2 col3 col4 col5 col6
0    A    B    C    D    E    F

If you have multiple rows it'll always reshape it into a single-row DF like this:

In [25]: df
Out[25]:
  col1 col2 col3
0    A    B    C
1    D    E    F
2    A    B    C
3    D    E    F

In [26]: pd.DataFrame(df.values.reshape(1,-1), columns=np.arange(1, df.size+1)) \
    ...:   .add_prefix('col')
Out[26]:
  col1 col2 col3 col4 col5 col6 col7 col8 col9 col10 col11 col12
0    A    B    C    D    E    F    A    B    C     D     E     F

or

In [33]: pd.DataFrame(df.values.reshape(-1,6), columns=np.arange(1, df.size//2+1)) \
    ...:   .add_prefix('col')
Out[33]:
  col1 col2 col3 col4 col5 col6
0    A    B    C    D    E    F
1    A    B    C    D    E    F
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419