How to insert a string into the Pandas multiindex framework?

I have a Pandas multi-index dataframe (Reg, Type, Part, IsExpired) -

Reg        Type      Part     IsExpired    Quantity
APAC       Disk      A        False        10
                              True         12
EMEA       Disk      A        False        22
EMEA       Disk      B        False        13
                              True         17

I want to make sure that each (Reg, Type, Part) tuple has True and False for IsExpired. For example. I would like to insert a row for (EMEA, Disk, A, True) -

Reg        Type      Part     IsExpired    Quantity
APAC       Disk      A        False        10
                              True         12
EMEA       Disk      A        False        22
                              True         0   <-- inserted row
EMEA       Disk      B        False        13
                              True         17
+3
source share
2 answers

You can unstackand then fillna:

In [11]: df2
Out[11]:
                          Quantity
Reg  Type Part IsExpired
APAC Disk A    False            10
               True             12
EMEA Disk A    False            22
          B    False            13
               True             17

In [12]: df2.unstack()
Out[12]:
               Quantity
IsExpired         False True
Reg  Type Part
APAC Disk A          10    12
EMEA Disk A          22   NaN
          B          13    17

In [13]: df2.unstack().fillna(0)
Out[13]:
               Quantity
IsExpired         False True
Reg  Type Part
APAC Disk A          10    12
EMEA Disk A          22     0
          B          13    17

Perhaps it makes sense to save this as a column? Otherwise, stack back:

In [14]: df2.unstack().fillna(0).stack()
Out[14]:
                          Quantity
Reg  Type Part IsExpired
APAC Disk A    False            10
               True             12
EMEA Disk A    False            22
               True              0
          B    False            13
               True             17
+2
source

Have you considered simply adding the appropriate line? Since you really just add one value cell, you can do this efficiently:

df.at[('EMEA', 'DISC', 'A', False), 'Quantity'] = 0 
0

Source: https://habr.com/ru/post/1606269/


All Articles