Pandas: Unmelt Dataframe To Add Arbitrary Number Of Columns?
I've got a dataframe df in Pandas that looks like this: stores product discount Westminster 102141 T Westminster 102142 F City o
Solution 1:
Use DataFrame.unstack
for reshape, only necessary create counter by GroupBy.cumcount
, last change ordering of second level and flatten MultiIndex in columns by map
:
df = (df.set_index(['stores', df.groupby('stores').cumcount().add(1)])
.unstack()
.sort_index(axis=1, level=1))
df.columns = df.columns.map('{0[0]}_{0[1]}'.format)
df = df.reset_index()
print (df)
stores discount_1 product_1 discount_2 product_2 discount_3 \
0 City of London T 102141.0 F 102142.0 T
1 Westminster T 102141.0 F 102142.0 NaN
product_3
0 102143.0
1 NaN
Post a Comment for "Pandas: Unmelt Dataframe To Add Arbitrary Number Of Columns?"