This is the original Dataframe: enter image description here What I wanted : I wanted to convert this above data-frame into this multi-indexed column data-frame : enter image description here I managed to do it by this piece of code :

# tols : original dataframe
cols = pd.MultiIndex.from_product([['A','B'],['Y','X'] 
tols.set_axis(cols, axis = 1, inplace = False)

What I tried : I tried to do this with the reindex method like this :

cols = pd.MultiIndex.from_product([['A','B'],['Y','X'], 
tols.reindex(cols, axis = 'columns')

it resulted in an output like this : enter image description here

My problem : As you could see in the output above all my original numerical values go missing on employing the reindex method. In the documentation page it was clearly mentioned : Conform DataFrame to new index with optional filling logic, placing NA/NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one. So i don't understand:

  • Where did i particularly err in employing the reindex method to lose my original values
  • How should i have employed the reindex method correctly to get my desired output
  • $\begingroup$ Has this question been sufficiently answered? $\endgroup$
    – Tasty213
    Aug 27 '19 at 10:48

Regarding your code the tols must be cols?

cols = pd.MultiIndex.from_product([['A','B'],['Y','X'] 
tols.set_axis(cols, axis = 1, inplace = False)

This must be:

cols = pd.MultiIndex.from_product([['A','B'],['Y','X'] 
cols.set_axis(cols, axis = 1, inplace = False)

Personally I would have removed nan with a default value before performing the multi-indexing.

df_noNAN = from_product.fillna(value=-1)

In your case it looks like the inplace is producing a bug and better reported to the pandas team. On Stack exchange they are extremely responsive.

  • $\begingroup$ cols is the multindex formed right ?....so I am applying this multindex cols to my original data frame tols... $\endgroup$
    – Arnav Das
    Aug 27 '19 at 10:57
  • $\begingroup$ Okay, yes I misread your code ... although you didn't mention the 'tols' dataframe. Anyway same idea "fillna" I my opinion would be a standard approach prior further manipulation. $\endgroup$
    – M__
    Aug 27 '19 at 12:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.