Unmelt Pandas DataFrame

You could use set_index and unstack

In [18]: df.set_index(['id', 'num', 'q'])['v'].unstack().reset_index()
Out[18]:
q  id  num    a     b    d     z
0   1   10  2.0   4.0  NaN   NaN
1   1   12  NaN   NaN  6.0   NaN
2   2   13  8.0   NaN  NaN   NaN
3   2   14  NaN  10.0  NaN   NaN
4   3   15  NaN   NaN  NaN  12.0

You're really close slaw. Just rename your column index to None and you've got what you want.

df2 = df.pivot_table(index=['id','num'], columns='q')
df2.columns = df2.columns.droplevel().rename(None)
df2.reset_index().fillna("null").to_csv("test.csv", sep="\t", index=None)

Note that the the 'v' column is expected to be numeric by default so that it can be aggregated. Otherwise, Pandas will error out with:

DataError: No numeric types to aggregate

To resolve this, you can specify your own aggregation function by using a custom lambda function:

df2 = df.pivot_table(index=['id','num'], columns='q', aggfunc= lambda x: x)

Tags:

Python

Pandas