问题
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