Home > Blockchain >  Pandas how to reorder my table or dataframe
Pandas how to reorder my table or dataframe

Time:08-27

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

table In

My desired output is:

table out

CodePudding user response:

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.sort_values('axis_x').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
  • Related