Pandas的索引index的用途

##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,时间类型索引,强大的日期和时间的方法支持;
'''

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值