CAPSLOCK
CAPSLOCK

Reputation: 6483

Pandas add column level which increases total columns count

I created a dataframe as follows.

myidx=['idx1','idx2','idx3']
mycols=['a','b','c','d']
df=pd.DataFrame(index=myidx,columns=mycols)
        a    b    c    d
idx1  NaN  NaN  NaN  NaN
idx2  NaN  NaN  NaN  NaN
idx3  NaN  NaN  NaN  NaN

Then I would like to add a new column level with n repeated values. Let say:

mycolsnewlvl=['foo','bar','baz']

The expected output would be:

             a              b              c              d   
       foo  bar  baz  foo  bar  baz  foo  bar  baz  foo  bar  baz
idx1   NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
idx2   NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
idx3   NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN

I have tried to follow this

df.columns = pd.MultiIndex.from_product([df.columns, ['foo','bar','baz']])

But it returns:

ValueError: Length mismatch: Expected axis has 8 elements, new values have 24 elements

I also had a look at this but couldn't make it work for my case.

Upvotes: 1

Views: 60

Answers (1)

jezrael
jezrael

Reputation: 862761

Use DataFrame.reindex for repeat columns by MultiIndex values:

mux = pd.MultiIndex.from_product([df.columns, ['foo','bar','baz']])

df = df.reindex(mux, axis=1)
print (df)
       a           b           c           d        
     foo bar baz foo bar baz foo bar baz foo bar baz
idx1 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
idx2 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
idx3 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

Upvotes: 2

Related Questions