This is an application of pivot which is covered extensively in How to pivot a dataframe? so I offer this Community wiki as a place to outline a solution in a way that is easier to understand than the comments. But encourage reading of the linked duplicate to understand fully.
The following pandas functions are useful here:
- pivot
- astype
- str.zfill
- add_prefix
- reset_index
Complete Working Example:
import pandas as pd
df = pd.DataFrame({'SKU': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2},
'Warehouse Num': {0: 1, 1: 2, 2: 3, 3: 1, 4: 2, 5: 3},
'Available Stock': {0: 45, 1: 0, 2: 6, 3: 9, 4: 32, 5: 7}})
# long to wide
new_df = df.pivot(index='SKU', columns='Warehouse Num',
values='Available Stock')
# pad columns and index with zeros to 3 places
new_df.columns = new_df.columns.astype(str).str.zfill(3).rename(None)
new_df.index = new_df.index.astype(str).str.zfill(3)
# Add Prefix and return SKU to a column
new_df = new_df.add_prefix('Warehouse ').reset_index()
print(new_df)
new_df:
SKU Warehouse 001 Warehouse 002 Warehouse 003
0 001 45 0 6
1 002 9 32 7