Pandas索引-第二次打卡

本文详细探讨了Pandas中的索引操作,包括单级索引的loc、iloc和[]方法,布尔索引及其符号,多级索引,快速标量索引,区间索引,以及如何处理重复数据和进行数据抽样。同时,解答了如何更改列或行顺序,选取子集,以及查询缺失值等常见问题。

索引

单级索引

loc方法、iloc方法、[]操作符
loc方法
df.loc[1102]
df.loc[[1102,2304]]
df.loc[1304:].head()
df.loc[2402::-1].head()
df.loc[:,'Height'].head()
df.loc[1102:2401:3,'Height':'Math'].head()#联合索引
df.loc[lambda x:x['Gender']=='M'].head()
iloc方法
df.iloc[3]
df.iloc[3:5]
df.iloc[:,3].head()#单列索引
df.iloc[:,7::-2].head()#每隔开一个显示(多边索引)
[]操作符
s = pd.Series(df['Math'],index=df.index)
s[1101]
#使用的是索引标签

s[0:4]
#使用的是绝对位置的整数切片,与元素无关,这里容易混淆

# DataFrame的[]操作
df[1:2]
#这里非常容易写成df['label'],会报错
#同Series使用了绝对位置切片
#如果想要获得某一个元素,可用如下get_loc方法:
row = df.index.get_loc(1102)
df[row:row+1]

布尔索引
布尔符号:’&’,’|’,’~’:分别代表和and,或or,取反not

loc和[]中相应位置都能使用布尔列表选择

快速标量索引

当只需要取一个元素时,at和iat方法能够提供更快的实现

display(df.at[1101,'School'])
display(df.loc[1101,'School'])
display(df.iat[0,0])
display(df.iloc[0,0])
区间索引
#interval_range方法
pd.interval_range(start=0,end=5)
#closed参数可选'left''right''both''neither',默认左开右闭

pd.interval_range(start=0,periods=8,freq=5)
#periods参数控制区间个数,freq控制步长

#利用cut将数值列转为区间为元素的分类变量
math_interval = pd.cut(df['Math'],bins=[0,40,60,80,100])
#注意,如果没有类型转换,此时并不是区间类型,而是category类型
math_interval.head()

#区间索引的选取
df_i = df.join(math_interval,rsuffix='_interval')[['Math','Math_interval']].reset_index().set_index('Math_interval')
df_i.head()

df_i.loc[65].head()

df_i[df_i.index.astype('interval').overlaps(pd.Interval(70, 85))].head()#选取某个区间

多级索引

#直接创建元组
tuples = [('A','a'),('A','b'),('B','a'),('B','b')]
mul_index = pd.MultiIndex.from_tuples(tuples, names=('Upper', 'Lower'))
pd.DataFrame({'Score':['perfect','good','fair','bad']},index=mul_index)

#利用zip创建元组
L1 = list('AABB')
L2 = list('abab')
tuples = list(zip(L1,L2))
mul_index = pd.MultiIndex.from_tuples(tuples, names=('Upper', 'Lower'))
pd.DataFrame({'Score':['perfect','good','fair','bad']},index=mul_index)

#通过Array创建
arrays = [['A','a'],['A','b'],['B','a'],['B','b']]
mul_index = pd.MultiIndex.from_tuples(arrays, names=('Upper', 'Lower'))
pd.DataFrame({'Score':['perfect','good','fair','bad']},index=mul_index)

#通过from_product
L1 = ['A','B']
L2 = ['a','b']
pd.MultiIndex.from_product([L1,L2],names=('Upper', 'Lower'))

#指定df中的列创建(set_index方法)
df_using_mul = df.set_index(['Class','Address'])

#多层索引切片
df_using_mul.sort_index().loc['C_2','street_5']
df_using_mul.sort_index().loc[('C_2','street_6'):('C_3','street_4')]
#注意此处由于使用了loc,因此仍然包含右端点

df_using_mul.sort_index().loc[('C_2','street_7'):'C_3'].head()
df_using_mul.sort_index().loc[[('C_2','street_7'),('C_3','street_2')]]
#表示选出某几个元素,精确到最内层索引

df_using_mul.sort_index().loc[(['C_2','C_3'],['street_4','street_7']),:]
#选出第一层在‘C_2’和'C_3'中且第二层在'street_4'和'street_7'中的行

L1,L2 = ['A','B','C'],['a','b','c']
mul_index1 = pd.MultiIndex.from_product([L1,L2],names=('Upper', 'Lower'))
L3,L4 = ['D','E','F'],['d','e','f']
mul_index2 = pd.MultiIndex.from_product([L3,L4],names=('Big', 'Small'))
df_s = pd.DataFrame(np.random.rand(9,9),index=mul_index1,columns=mul_index2)

df_s.loc[idx['B':,df_s['D']['d']>0.3],idx[df_s.sum()>4]]
#df_s.sum()默认为对列求和,因此返回一个长度为9的数值列表

#索引交换
df_using_mul.swaplevel(i=1,j=0,axis=0).sort_index().head()
df_muls = df.set_index(['School','Class','Address'])
df_muls.reorder_levels([2,0,1],axis=0).sort_index().head()
#如果索引有name,可以直接使用name
df_muls.reorder_levels(['Address','School','Class'],axis=0).sort_index().head()

索引设定

pd.read_csv('data/table.csv',index_col=['Address','School']).head()
df.reindex(columns=['Height','Gender','Average']).head()

常用索引型函数

query函数中的布尔表达式中,下面的符号都是合法的:行列索引名、字符串、and/not/or/&/|/~/not in/in/==/!=、四则运算符
mask函数与where功能上相反,其余完全一致,即对条件为True的单元进行填充

重复语速处理

duplicated
drop_duplicates

抽样函数

sample

问题

如何更改列或行的顺序?
答案:用df.iloc[indexs, :]或者reindex index改行的顺序,用df.iloc[:, columns]或者eindex columns改列的顺序

如何交换奇偶行(列)的顺序?
答案:
奇偶行换

a = []
ou = []
qi = []
for i in df.index:
    a.append(i)
for i in range(len(a)):
    if i % 2 == 0:
        ou.append(i)
    if i % 2 != 0:
    	qi.append(i)  
def xmerge(a, b):
    alen, blen = len(a), len(b)
    mlen = min(alen, blen)
    for i in range(mlen):
        yield a[i]
        yield b[i]

    if alen > blen:
        for i in range(mlen, alen):
            yield a[i]
    else:
        for i in range(mlen, blen):
            yield b[i]

d = [i for i in xmerge(qi, ou)]
df.iloc[d, :]

奇偶列换

a = []
ou = []
qi = []
for i in df.columns:
    a.append(i)
for i in range(len(a)):
    if i % 2 == 0:
        ou.append(i)
    if i % 2 != 0:
    	qi.append(i)  
def xmerge(a, b):
    alen, blen = len(a), len(b)
    mlen = min(alen, blen)
    for i in range(mlen):
        yield a[i]
        yield b[i]

    if alen > blen:
        for i in range(mlen, alen):
            yield a[i]
    else:
        for i in range(mlen, blen):
            yield b[i]

d = [i for i in xmerge(qi, ou)]
df.iloc[:, d]

如果要选出DataFrame的某个子集,请给出尽可能多的方法实现。
答案:df.loc\ df.iloc\ df[]\ df[df[]判断]

query函数比其他索引方法的速度更慢吗?在什么场合使用什么索引最高效?
答案:比其他更快,在表格特别大的时候使用query更高效

单级索引能使用Slice对象吗?能的话怎么使用,请给出一个例子。
答案:可以。

idx=pd.IndexSlice
df.loc[idx[df['Weight']<60]]

如何快速找出某一列的缺失值所在索引?
答案:df[df.isnull().values==True]

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值