Guy Van-Dam
Guy Van-Dam

Reputation: 43

Reshape Pandas DataFrame to a Series with columns prefixed with indices

Say I have a Pandas DataFrame like this one:

      A    B
idx1  1    3
idx2  2    4

Is there a pandas function that converts this table to something like this?

A_idx1  A_idx2 B_idx1 B_idx
1       2      3      4

Upvotes: 3

Views: 99

Answers (1)

jezrael
jezrael

Reputation: 863166

Use DataFrame.unstack, convert to DataFrame and transpose, last join MultiIndex in columns:

df1 = df.unstack().to_frame().T
df1.columns = df1.columns.map('_'.join)
print (df1)
   A_idx1  A_idx2  B_idx1  B_idx2
0       1       2       3       4

Upvotes: 3

Related Questions