##Pandas的索引index的用途
'''把数据存储于普通的column列也能用于数据查询,那使用index有什么好处?index的用途总结:
1.更方便的数据查询;
2.使用index可以获得性能提升;
3.自动的数据对齐功能;
4.更多更强大的数据结构支持;'''
import pandas as pd
df =pd.read_csv('F:\\python387\\pandas\\antlearnpandasmaster\\datas\\ml_latest_small\\ratings.csv')
#1.使用index查询数据
#drop == False,让索引列还保持在column
df.set_index('userId',inplace=True,drop = False)#去掉drop = False,删除userId列
#print(df.index)
#使用index的查询方法
#print(df.loc[500])
#print(df.loc[df['userId']]==500)
#使用index会提升查询性能
'''
·如果index是唯一的,Pandas会使用哈希表优化,查询性能为O(1);
·如果index不是唯一的,但是有序,Pandas会使用二分查找算法,查询性能为O(logN)
.如果index是完全随机的,那么每次查询都要扫描全表,查询性能为O(N);'''
#实验1:完全随机的顺序查询
#将数据随机打散
from sklearn.utils import shuffle
df_shuffle = shuffle(df)
#print(df_shuffle.head())
print(df_shuffle.index.is_monotonic_increasing)
print(df_shuffle.index.is_unique)
print(df_shuffle.loc[500])
#实验2.将index排序后的查询
df_sorted = df_shuffle.sort_index()
#print(df_sorted)
#print(df_sorted.index.is_monotonic_increasing)
#print(df_sorted.index.is_unique)
#3.使用index能自动对齐数据
s1 = pd.Series([1,2,3],index=list('abc'))
#print(s1)
s2 = pd.Series([2,3,4],index=list('bcd'))
#print(s2)
#print(s1+s2)
#使用index更多更强大的数据结构支持
'''很多强大的索引数据结构
. Categoricallndex,基于分类数据的Index,提升性能;
-Multilndex,多维索引,用于groupby多维聚合后结果等;
. Datetimelndex,时间类型索引,强大的日期和时间的方法支持;
'''
Pandas的索引index的用途
最新推荐文章于 2025-03-18 16:19:57 发布