Say I have a dataframe which looks like following,
df1.head()
ID NAMES
SAP KASF
SAP HJL
SAP KJOP
LUF LNC1
LUF LNC2
LUF KASF
LUF HJL
And I need to reshape the above dataframe as the following, with NAMES
as rows and the values in column ID
as columns/headers and fill with 1 or 0.
The values to fill in is based on the matching value in the column NAME
for each ID
.
df.head()
NAMES SAP LUF
KASF 1 1
HJL 1 1
KJOP 1 0
LNC1 0 1
LNC2 0 1
I have tried,
df.pivot(index='NAME',columns='ID')
And it is throwing,
ValueError: Index contains duplicate entries, cannot reshape
Other solution I tried is,
(
df.T
.set_axis(["ID"],axis=True, inplace=False)
.rename_axis('NAME',axis=0)
.reset_index()
)
Which also throwing error due to mismatching vaues for ID
and NAME