DasBoeseC
DasBoeseC

Reputation: 23

Add a column name to a panda dataframe (multi index)

I concatenate series objects, with existing column names together to a DataFrame in Pandas. The result looks like this:

pd.concat([x, y, z], axis=1)


   X   |  Y   |   Z
  -------------------
  data | data | data

Now I want to insert another column name A above the column names X, Y, Z, for the whole DataFrame. This should look like this at the end:

   A                  # New Column Name
  ------------------- 
   X   |  Y   |   Z   # Old Column Names
  -------------------
  data | data | data 

So far I did not find a solution how to insert a column name A above the existing columns names X, Y, Z for the complete DataFrame. I would be grateful for any help. :)

Upvotes: 2

Views: 753

Answers (1)

Shubham Sharma
Shubham Sharma

Reputation: 71689

Let's try with MultiIndex.from_product to create MultiIndex columns:

df = pd.concat([x, y, z], axis=1)
df.columns = pd.MultiIndex.from_product([['A'], df.columns])

A            
X     Y     Z
data  data  data

Upvotes: 2

Related Questions