Reputation: 417
I have a single-level pandas dataframe:
df = pd.DataFrame({"x":[0,0,0],"y":[0,0,0]})
which looks like this:
x y
0 0 0
1 0 0
2 0 0
Now I want to add a multi-level column "z" (with two sub-columns "z1 and "z2") to this dataframe, so it'll look like this:
x y z
z1 z2
0 0 0 1 2
1 0 0 1 2
2 0 0 1 2
Upvotes: 3
Views: 2508
Reputation: 8219
First we make the existing columns multi-index:
df.columns = pd.MultiIndex.from_arrays([df.columns,['']*len(df.columns)])
and then add new ones indexed by tuples
df[('z','z1')] = [1,1,1]
df[('z','z2')] = [2,2,2]
df
to get
x y z
z1 z2
0 0 0 1 2
1 0 0 1 2
2 0 0 1 2
Upvotes: 2