I have this dataframe:
df = pd.DataFrame({'NUMBER_1': {('2019-07', 'A'): 4, ('2019-07', 'D'): 2, ('2019-08', 'A'): 32, ('2019-08', 'B'): 14, ('2019-09', 'A'): 32, ('2019-09', 'B'): 53, ('2019-09', 'C'): 54, ('2019-09', 'D'): 24},
'NUMBER_2': {('2019-07', 'A'): 75, ('2019-07', 'D'): 12, ('2019-08', 'A'): 42, ('2019-08', 'B'): 32, ('2019-09', 'A'): 54, ('2019-09', 'B'): 21, ('2019-09', 'C'): 97, ('2019-09', 'D'): 65}})
df
:
Where I'm looking for this output:
I have seen similar questions for categorical types columns, but not for indexes and I'm looking for a way to avoid using the method reset_index()
as actually I'm using four indexes and not just two as in the minimal example. Any suggestions?
The reindex() function is used to conform Series to new index with optional filling logic, placing NA/NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and copy=False. Method to use for filling holes in reindexed DataFrame.
Setting index The column you want to index does not need to have unique values.
Reindexing the columns using axis keyword One can reindex a single column or multiple columns by using reindex() method and by specifying the axis we want to reindex. Default values in the new index that are not present in the dataframe are assigned NaN.
You can define a MultiIndex
using the current MultiIndex.levels
, and reindex
setting fill_value
to 0
:
df.reindex(pd.MultiIndex.from_product(df.index.levels), fill_value=0)
NUMBER_1 NUMBER_2
2019-07 A 4 75
B 0 0
C 0 0
D 2 12
2019-08 A 32 42
B 14 32
C 0 0
D 0 0
2019-09 A 32 54
B 53 21
C 54 97
D 24 65
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With