from decimal import Decimal
import pandas as pd
df = pd.DataFrame([
["1000123797207765", 0, 129.26, 0, 29.26],
], columns=pd.MultiIndex.from_tuples(
[
("", "ID"),
("2022-09-01", "origin"),
("2022-09-01", "checked"),
("2022-09-02", "origin"),
("2022-09-02", "checked"),
]
))
2022-09-01 2022-09-02
ID origin checked origin checked
0 1000123797207765 0 129.26 0 29.26
As above codes showed, I get a dataframe. Now I want to reset index to get a dataframe with below format
2022-09-01 2022-09-02
ID origin checked origin checked
1000405797207765 0 129.26 0 29.26
How can I make it? Great thanks.
CodePudding user response:
In pandas reset index mean set to default value, if need 'remove'
first 0
is possible convert first column to index
.
Reason is pandas DataFrame always has index.
print (df.index)
RangeIndex(start=0, stop=1, step=1)
df = df.set_index([('','ID')]).rename_axis('ID')
print (df)
2022-09-01 2022-09-02
origin checked origin checked
ID
1000123797207765 0 129.26 0 29.26
print (df.index)
Index(['1000123797207765'], dtype='object', name='ID')
CodePudding user response:
What you want to do is to use the column "ID" as the index of the DataFrame. This can be done by the following line of code:
df = df.set_index('ID')