1.set_index
DataFrame可以通过set_index方法,可以设置单索引和复合索引。
DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)
append添加新索引,drop为False,inplace为True时,索引将会还原为列
import numpy as np
import pandas as pd
from pandas import DataFrame
a_data=pd.DataFrame({"a_char":list("abcd"),
"number":[1,1,2,2],
"subject":["maths","science","chem","history"],
"score":[100,90,80,90]})
a_data.index=["A","B","C","D"]
print(a_data)
"""
a_char number subject score
A a 1 maths 100
B b 1 science 90
C c 2 chem 80
D d 2 history 90
"""
a_data1=a_data.set_index("subject")
print(a_data1)
"""
a_char number score
subject
maths a 1 100
science b 1 90
chem c 2 80
history d 2 90
"""
a_data2=a_data.set_index(["number","subject"])
print(a_data2)
""" a_char score
number subject
1 maths a 100
science b 90
2 chem c 80
history d 90
"""
reset_index可以还原索引,重新变为默认的整型索引
DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill=”)
level控制了具体要还原的那个等级的索引
drop为False则索引列会被还原为普通列,否则会丢失
a_data3=a_data2.reset_index()
print(a_data3)
"""
number subject a_char score
0 1 maths a 100
1 1 science b 90
2 2 chem c 80
3 2 history d 90
"""
参考:https://blog.csdn.net/jingyi130705008/article/details/78162758/
以上,记录本人学习过程