3

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
2
  • your life is probably easier if you just add columns df["z1"] = 1; df["z2"] = 2 Commented Mar 31, 2021 at 0:45
  • @anon01 Well in reality I need multiple multi-level columns in my dataframe, each with multiple sub-columns, and I often need to manipulate all sub-columns of a given parent column. If I don't use multi-level columns, then each time I need to do a list comprehension to choose all columns that start with a given string (e.g. all columns that start with a "z", i.e. "z1" and "z2"), so it'll a bit messy. So, if there is an easy way to add multi-level columns to single-level dataframes, that'll make my job easier I guess. Commented Mar 31, 2021 at 1:01

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.