I would like to get from the first dataframe to the second? How can I do this? Can`t change the dataframe structure upfront.
Dummy Code:
index1 = [("x","1"), ("x","3"), ("x","5"), ("y","1"), ("y","3")]
data = pd.DataFrame(index = pd.MultiIndex.from_tuples(index1), columns = ["A","B"])
data.loc[("x","sum"),:] = [19,10]
index2 = [("x","1"), ("x","3"), ("x","5"), ("x","sum"), ("y","1"), ("y","3")]
data2 = pd.DataFrame(index = pd.MultiIndex.from_tuples(index2), columns = ["A","B"])
CodePudding user response:
You can sort_index
by level=0
:
data.sort_index(level=0)
A B
x 1 NaN NaN
3 NaN NaN
5 NaN NaN
sum 19 10
y 1 NaN NaN
3 NaN NaN