简体   繁体   中英

Rearrange Python Pandas DataFrame Rows into a Single Row

I have a Pandas dataframe that looks something like:

df = pd.DataFrame({'col1': [1, 2, 3, 4], 'col2': [5, 6, 7, 8]}, index=['A', 'B', 'C', 'D'])

    col1    col2
A   1       50
B   2       60
C   3       70
D   4       80

However, I want to automatically rearrange it so that it looks like:

    col1 A    col1 B    col1 C    col1 D    col2 A    col2 B    col2 C    col2 D
0   1         2         3         4         50        60        70        80
  1. I want to combine the row name with the column name
  2. I want to end up with only one row
df2 = df.unstack()
df2.index = [' '.join(x) for x in df2.index.values]
df2 = pd.DataFrame(df2).T

df2

    col1 A  col1 B  col1 C  col1 D  col2 A  col2 B  col2 C  col2 D
0   1       2       3       4       5       6       7       8

If you want to have the orignal x axis labels in front of the column names ("A col1"...) just change .join(x) by .join(x[::-1]) :

df2 = df.unstack()
df2.index = [' '.join(x[::-1]) for x in df2.index.values]
df2 = pd.DataFrame(df2).T

df2

    A col1  B col1  C col1  D col1  A col2  B col2  C col2  D col2
0   1       2       3       4       5       6       7       8

Here's one way to do it, there could be a simpler way

In [562]: df = pd.DataFrame({'col1': [1, 2, 3, 4], 'col2': [50, 60, 70, 80]}, 
                           index=['A', 'B', 'C', 'D'])

In [563]: pd.DataFrame([df.values.T.ravel()], 
                       columns=[y+x for y in df.columns for x in df.index])
Out[563]:
   col1A  col1B  col1C  col1D  col2A  col2B  col2C  col2D
0      1      2      3      4     50     60     70     80

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM