[英]Pandas dataframe reset index
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.如上代码所示,我得到一个 dataframe。 Now I want to reset index to get a dataframe with below format现在我想重置索引以获得具有以下格式的 dataframe
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.太谢谢了。
In pandas reset index mean set to default value, if need 'remove'
first 0
is possible convert first column to index
.在 pandas 中重置索引意味着设置为默认值,如果需要'remove'
第一个0
可以将第一列转换为index
。
Reason is pandas DataFrame always has index.原因是 pandas DataFrame 总是有索引。
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')
What you want to do is to use the column "ID" as the index of the DataFrame.您要做的是使用“ID”列作为 DataFrame 的索引。 This can be done by the following line of code:这可以通过以下代码行来完成:
df = df.set_index('ID')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.