How can I add a level to a MultiIndex?

2024/10/9 14:25:15
index = [np.array(['foo', 'foo', 'qux']),np.array(['a', 'b', 'a'])]
data = np.random.randn(3, 2)
columns = ["X", "Y"]
df = pd.DataFrame(data, index=index, columns=columns)
df.index.names = ["Level0", "Level1"]
print dfX         Y
Level0 Level1                    
foo    a       0.418549  0.252685b      -1.307099  0.202833
qux    a       0.046095 -0.968976

New level

I want to take the index of df and create a new MultiIndex that now has an additional level.

new_level_name = "New level"
new_level_labels = ['p', 'q']
# new_multi-index 

Desired MultiIndex

Level0 Level1 Level2                    
foo    a      p       q       b      p      q       
qux    a      p      q      
Answer

The simpliest is use stack with new DataFrame with columns by new level values:

df1 = pd.DataFrame(data=1,index=df.index, columns=new_level_labels).stack()
df1.index.names = ['Level0','Level1',new_level_name]
print (df1)
Level0  Level1  New level
foo     a       p            1q            1b       p            1q            1
qux     a       p            1q            1
dtype: int64print (df1.index)
MultiIndex(levels=[['foo', 'qux'], ['a', 'b'], ['p', 'q']],labels=[[0, 0, 0, 0, 1, 1], [0, 0, 1, 1, 0, 0], [0, 1, 0, 1, 0, 1]],names=['Level0', 'Level1', 'New level'])
https://en.xdnf.cn/q/70007.html

Related Q&A

decoupled frontend and backend with Django, webpack, reactjs, react-router

I am trying to decouple my frontend and my backend in my project. My frontend is made up of reactjs and routing will be done with react-router, My backend if made form Django and I plan to use the fron…

Map colors in image to closest member of a list of colors, in Python

I have a list of 19 colors, which is a numpy array of size (19,3):colors = np.array([[0, 0, 0], [0, 0, 255], [255, 0, 0], [150, 30, 150], [255, 65, 255], [150, 80, 0], [170, 120, 65], [125, 125,…

Storing a file in the clipboard in python

Is there a way to use the win32clipboard module to store a reference to a file in the windows clipboard in python. My goal is to paste an image in a way that allows transparency. If I drag and drop a…

retrieve intermediate features from a pipeline in Scikit (Python)

I am using a pipeline very similar to the one given in this example : >>> text_clf = Pipeline([(vect, CountVectorizer()), ... (tfidf, TfidfTransformer()), ... …

Any way to do integer division in sympy?

I have a very long expression that I think can be simplified, and I thought sympy would be the perfect way to do it. Unfortunately the formula relies on a couple of integer divides, and I cant find any…

Scrapy LinkExtractor - Limit the number of pages crawled per URL

I am trying to limit the number of crawled pages per URL in a CrawlSpider in Scrapy. I have a list of start_urls and I want to set a limit on the numbers pages are being crawled in each URL. Once the l…

Python Invalid format string [duplicate]

This question already has answers here:Python time formatting different in Windows(3 answers)Closed 9 years ago.I am trying to print the date in the following format using strftime: 06-03-2007 05:40PMI…

Python template safe substitution with the custom double-braces format

I am trying to substitute variables in the format {{var}} with Pythons Template. from string import Templateclass CustomTemplate(Template):delimiter = {{pattern = r\{\{(?:(?P<escaped>\{\{)|(?P…

Emit signal in standard python thread

I have a threaded application where I do have a network thread. The UI-part passes a callback to this thread. The thread is a normal python thread - its NO QThread.Is it possible to emit PyQT Slot with…

Sqlalchemy from_statement() cannot locate column

I am following the sqlalchemy tutorial in http://docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.htmlNevertheless, instead of using a SQLite backend, I am using MySQL. The problem is that when I try to exe…