2

I've seen a lot of answers on flattening multi-level index. I just want to remove the very first index column on the left of this multi-index dataframe.

From this:

Attributes       Date    Close    Close               
Symbols                   AMZN      ^DJI  
0          2020-12-01  3220.08  29823.92  
1          2020-11-30  3168.04  29638.64  
2          2020-11-27  3195.34  29910.37  
3          2020-11-25  3185.07  29872.47

I'm looking for this outcome:

       Date    Close    Close               
               AMZN      ^DJI  
2020-12-01  3220.08  29823.92  
2020-11-30  3168.04  29638.64  
2020-11-27  3195.34  29910.37  
2020-11-25  3185.07  29872.47

Is this possible?

5
  • if I export to CSV -- df.to_csv("my_data.csv", index=False) -- I'm able to drop the index, but I'm not sure how to do it without exporting to csv. Commented Dec 2, 2020 at 6:06
  • 1
    index is fundamental to a dataframe and will always be there. However, you can do, df = df.reset_index(drop=True) , but an index will still be there of 0,1,2,3,4, etc. Commented Dec 2, 2020 at 6:07
  • I thought so too, but your code is not dropping that attirbutes/symbols part. Commented Dec 2, 2020 at 6:09
  • This is what I get when I print(df.columns) MultiIndex([( 'Date', ''), ( 'Close', 'AMZN'), ( 'Close', '^DJI'), ( 'High', 'AMZN'), ( 'High', '^DJI'), ( 'Low', 'AMZN'), ( 'Low', '^DJI'), ( 'Open', 'AMZN'), ( 'Open', '^DJI'), ('Volume', 'AMZN'), ('Volume', '^DJI')], names=['Attributes', 'Symbols']) Commented Dec 2, 2020 at 6:10
  • 1
    You can rename it to '' (blank) if that is what you mean: pandas.pydata.org/docs/reference/api/pandas.Index.rename.html Commented Dec 2, 2020 at 6:10

2 Answers 2

2

If need set first MultiIndex column to index use DataFrame.set_index with rename index and columns names by DataFrame.rename_axis - so output is DataFrame with DatetimeIndex:

df = df.set_index([('Date', '')]).rename_axis(index=None, columns=('Date',''))
print (df)
Date          Close          
               AMZN      ^DJI
2020-12-01  3220.08  29823.92
2020-11-30  3168.04  29638.64
2020-11-27  3195.34  29910.37
2020-11-25  3185.07  29872.47
Sign up to request clarification or add additional context in comments.

4 Comments

Hi @jezrael, I tried that but I get: raise TypeError("Must pass list-like as names.") TypeError: Must pass list-like as names.
@AdamSchroeder - My typo, sorry, need columns=('Date','')
@jezrael how about removing the AMZN without altering the structure?
@ira - Remove not possible, only rename like df = df.rename(columns={'AMZN':''})
0

If I've understood correctly, this is easiest way to do it:

df.reset_index().drop(columns="Attributes", axis = 1)

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.