'i want to convert all these rows and columns into 2 rows like this from

A B C D
X 1 2 3
Y 5 6 7
Z 11 12 13

I want to convert the above data frame like this

XA XB XC XD YA ..... ZD
1 2 3 4 5 14

please help me with this



Solution 1:[1]

Use:

s = df.stack()
new_df = s.to_frame().T.set_axis([f'{x}{y}' for x, y in s.index], axis=1)

   XA  XB  XC  XD  YA  YB  YC  YD  ZA  ZB  ZC  ZD
0   1   2   3   4   5   6   7   8  11  12  13  14

Solution 2:[2]

Here's a possible way. First, pd.melt your data in all its columns but keep the original index:

>>> df df = pd.melt(df, value_vars=df.columns, ignore_index=False)
>>> df df
      variable  value
X        A      1
Y        A      5
Z        A     11
X        B      2
Y        B      6
Z        B     12
X        C      3
Y        C      7
Z        C     13
X        D      4
Y        D      8
Z        D     14

Now set the new index and transpose the data:

>>> df df = df[["value"]].set_index(df.index + df["variable"]).T
>>> df 
       XA  YA  ZA  XB  YB  ZB  XC  YC  ZC  XD  YD  ZD
value   1   5  11   2   6  12   3   7  13   4   8  14

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ansev
Solution 2