create the tuple multi index for two index levels where level 0 is 1 and 2 and level 1 is a,b,c,d,e,f. Next extract A as a list of No 1 values and B as a list of No 2 values. Create the multi index and then create dataframe df2 using the lst_1 and lst_2 values for A and B and set the index to the multi-level index.
data="""No a b c d e f
1 34 43 29 78 29 68
2 29 28 57 39 10 37
"""
df = pd.read_csv(StringIO(data), sep="\s+").reset_index()
df.reset_index(inplace=True)
print(df.columns)
lst=[(1,'a'),(1,'b'),
(2,'c'),(2,'d'),
(3,'e'),(3,'f')
]
index=pd.MultiIndex.from_tuples(lst,names=['ID1','ID2'])
exclude=["No","level_0","index"]
columns=[x for x in df.columns if x not in exclude]
lst_1=np.array(df[df['No']==1][columns].unstack())
lst_2=np.array(df[df['No']==2][columns].unstack())
print(lst_1)
print(lst_2)
df2=pd.DataFrame({'A':lst_1,'B':lst_2},index=index)
print(df2)
output:
A B
ID1 ID2
1 a 34 29
b 43 28
2 c 29 57
d 78 39
3 e 29 10
f 68 37
fp=df2.pivot_table(columns=['ID1','ID2'])
print(fp)
output
ID1 1 2 3
ID2 a b c d e f
A 34 43 29 78 29 68
B 29 28 57 39 10 37