How to insert a row in a Pandas multiindex dataframe?

拥有回忆 提交于 2019-12-10 16:03:00

问题


I have a Pandas dataframe with a multiindex (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 every (Reg, Type, Part) tuple has True and False for IsExpired. E.g. I'd 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

回答1:


You could unstack and 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 keep this as a column? Otherwise stack it 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:


Have you considered just adding the relevant row? Since you're really just adding one cell of a value you could do it efficiently like this:

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


来源:https://stackoverflow.com/questions/29504597/how-to-insert-a-row-in-a-pandas-multiindex-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!