Skip to content Skip to sidebar Skip to footer

Convert Header Into Row

I have a table like this. user 01/12/15 02/12/15 someBool u1 100 300 true u2 200 -100 false u3 -50 200 true I want to re

Solution 1:

You need melt:

df = pd.melt(df, id_vars=['user','someBool'], var_name='date')
print (df)
  user someBool      datevalue0   u1     True01/12/151001   u2    False01/12/152002   u3     True01/12/15-503   u1     True02/12/153004   u2    False02/12/15-1005   u3     True02/12/15200

Another solution with stack:

df = df.set_index(['user','someBool'])
       .stack()
       .reset_index(name='value')
       .rename(columns={'level_2':'date'})
print (df)
  user someBool      date  value
0   u1     True01/12/151001   u1     True02/12/153002   u2    False01/12/152003   u2    False02/12/15   -1004   u3     True01/12/15    -505   u3     True02/12/15200

Solution 2:

numpy reconstruct the whole thing

id_vars = ['user', 'someBool']

the_rest = df.columns.difference(id_vars).tolist()
m, n = len(df), len(the_rest)
var_slc = np.arange(m).repeat(n)

pd.DataFrame(
    np.hstack([
            df[id_vars].values[var_slc],
            np.tile(the_rest, m)[:, None],
            df[the_rest].values.reshape(-1, 1)
        ]), columns=id_vars + ['date', 'value']
)

  user someBool      datevalue0   u1     True01/12/151001   u1     True02/12/153002   u2    False01/12/152003   u2    False02/12/15-1004   u3     True01/12/15-505   u3     True02/12/15200

Post a Comment for "Convert Header Into Row"