Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a multi-level column to a single-level pandas dataframe

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
like image 260
AAriam Avatar asked Mar 18 '26 08:03

AAriam


1 Answers

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
like image 108
piterbarg Avatar answered Mar 19 '26 23:03

piterbarg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!