Pandas how to reorder my table or dataframe

Question:

I have a dataframe in pandas where each column has different value range. For example:

table In

My desired output is:

table out

Asked By: francisco hoquee

||

Answers:

First, it makes 2-level index, then unstack based on multiindex and, finally, rename columns.

df = pd.DataFrame({'axis_x': [0, 1, 2, 0, 1, 2, 0, 1, 2], 'axis_y': [0, 0, 0, 1, 1, 1, 2, 2, 2],
                   'data': ['diode', 'switch', 'coil', '$2.2', '$4.5', '$3.2', 'colombia', 'china', 'brazil']})
df = df.set_index(['axis_x', 'axis_y']).unstack().rename(columns={0: 'product', 1: 'price', 2: 'country'})
print(df)

Prints:

          data                
axis_y product price   country
axis_x                        
0        diode  $2.2  colombia
1       switch  $4.5     china
2         coil  $3.2    brazil
Answered By: Алексей Р
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.