Dataframe convert to one row with new columns, from old row and old columns

Question:

A dataframe as below and I want to convert it to one row, with new columns created from its original rows and columns,

data = {'Contract' : ["Team A", "Team B", "Team C"],
'Revenue': [11,7,10],
'Cost' : [5,2,9],
'Tax' : [4,2,2]}

like:

enter image description here

I tried:

import pandas as pd
df = pd.DataFrame(data)

print (df.values.flatten())

The result is not ideal:

['Team A' 5L 11L 4L 'Team B' 2L 7L 2L 'Team C' 9L 10L 2L]

How can I achieve it?

Asked By: Mark K

||

Answers:

Check

s = df.set_index('Contract').stack().to_frame(0).T
s.columns=s.columns.map('_'.join)
s
   Team A_Revenue  Team A_Cost  ...  Team C_Cost  Team C_Tax
0              11            5  ...            9           2
[1 rows x 9 columns]
Answered By: BENY
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.