DataFrame Pandas - Flatten dataframe using index and column name as the new column name

Viewed 116

Here's my problem.

I have a data frame like this

   A B C
d1 1 2 3
d2 4 5 6

I want to generate the dataframe like this.

   A-d1 B-d1 C-d1 A-d2 B-d2 C-d2
    1    2    3    4    5    6
1 Answers

Use stack for Series with MultiIndex, then flatten it in list comprehension and pass to DataFrame constructor:

s = df.stack()
#python 3.6+
df1 = pd.DataFrame([s.values],  columns=[f'{j}-{i}' for i, j in s.index])
#python bellow 3.6
#df1 = pd.DataFrame([s.values],  columns=['{}-{}'.format(i, j) for i, j in s.index])
print (df1)
   A-d1  B-d1  C-d1  A-d2  B-d2  C-d2
0     1     2     3     4     5     6

Or flatten data by numpy.ravel and create new columns by itertools.product:

from  itertools import product

c = [f'{j}-{i}' for i, j in product(df.index, df.columns)]
df1 = pd.DataFrame([df.values.ravel()], columns=c)
print (df1)
   A-d1  B-d1  C-d1  A-d2  B-d2  C-d2
0     1     2     3     4     5     6
Related