CH02 - Pandas【索引】

本文深入探讨Pandas库中的数据索引与操作技巧,包括单级与多级索引的使用方法,如loc、iloc及[]操作符,以及数据筛选、排序与重置索引等高级功能。通过实例讲解,帮助读者掌握高效的数据处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import numpy as np
import pandas as pd
df = pd.read_csv('C:/Users/admin/Desktop/joyful-pandas-master/joyful-pandas-master/data/table.csv',index_col = 'ID')
df.head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1101S_1C_1Mstreet_11736334.0A+
1102S_1C_1Fstreet_21927332.5B+
1103S_1C_1Mstreet_21868287.2B+
1104S_1C_1Fstreet_21678180.4B-
1105S_1C_1Fstreet_41596484.8B+

一、单级索引

1.1、loc方法、iloc方法、[]操作符

  • 常见的三类索引方法:
    • iloc表示位置索引;
    • loc表示标签索引;
    • []也具有很大的便利性.

1.1.1、loc方法(注意:所有在loc中使用的切片全部包含右端点!)

1. 单行索引

df.loc[1103]
School          S_1
Class           C_1
Gender            M
Address    street_2
Height          186
Weight           82
Math           87.2
Physics          B+
Name: 1103, dtype: object

2. 多行索引

df.loc[[1102,2304]]
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1102S_1C_1Fstreet_21927332.5B+
2304S_2C_3Fstreet_61648195.5A-
df.loc[1304:].head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1304S_1C_3Mstreet_21957085.2A
1305S_1C_3Fstreet_51876961.7B-
2101S_2C_1Mstreet_71748483.3C
2102S_2C_1Fstreet_61616150.6B+
2103S_2C_1Mstreet_41576152.5B-
df.loc[2402::-1].head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
2402S_2C_4Mstreet_71668248.7B
2401S_2C_4Fstreet_21926245.3A
2305S_2C_3Mstreet_41877348.9B
2304S_2C_3Fstreet_61648195.5A-
2303S_2C_3Fstreet_71909965.9C
  • python中双冒号“::”代表切片。X[a::b]代表从X序列的a(索引序号)开始取值,步长为b,若b为负值,则倒序切片

3. 单列索引

df.loc[:,'Height'].head()
ID
1101    173
1102    192
1103    186
1104    167
1105    159
Name: Height, dtype: int64

4. 多行索引

df.loc[:,['Height','Math']].head()
HeightMath
ID
110117334.0
110219232.5
110318687.2
110416780.4
110515984.8
df.loc[:,'Height':'Math'].head()
HeightWeightMath
ID
11011736334.0
11021927332.5
11031868287.2
11041678180.4
11051596484.8

5. 联合索引

df.loc[1102:2401:3,'Height':'Math'].head()
HeightWeightMath
ID
11021927332.5
11051596484.8
12031605358.8
13011616831.5
13041957085.2

6. 函数式索引

df.loc[lambda x : x['Gender']=='M'].head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1101S_1C_1Mstreet_11736334.0A+
1103S_1C_1Mstreet_21868287.2B+
1201S_1C_2Mstreet_51886897.0A-
1203S_1C_2Mstreet_61605358.8A+
1301S_1C_3Mstreet_41616831.5B+
def f(x):
    return [1101,1103]
df.loc[f]
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1101S_1C_1Mstreet_11736334.0A+
1103S_1C_1Mstreet_21868287.2B+

7. 布尔索引

df.loc[df['Address'].isin(['street_4','street_7'])].head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1105S_1C_1Fstreet_41596484.8B+
1202S_1C_2Fstreet_41769463.5B-
1301S_1C_3Mstreet_41616831.5B+
1303S_1C_3Mstreet_71888249.7B
2101S_2C_1Mstreet_71748483.3C
df.loc[[True if i[-1] == '4' or i[-1] == '7' else False for i in df['Address'].values]].head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1105S_1C_1Fstreet_41596484.8B+
1202S_1C_2Fstreet_41769463.5B-
1301S_1C_3Mstreet_41616831.5B+
1303S_1C_3Mstreet_71888249.7B
2101S_2C_1Mstreet_71748483.3C

1.1.2、iloc方法(注意与loc不同,切片右端点不包含)

1. 单列索引

df.iloc[3]
School          S_1
Class           C_1
Gender            F
Address    street_2
Height          167
Weight           81
Math           80.4
Physics          B-
Name: 1104, dtype: object

2. 多行索引

df.iloc[3:5]
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1104S_1C_1Fstreet_21678180.4B-
1105S_1C_1Fstreet_41596484.8B+

3. 单列索引

df.iloc[:,3].head()
ID
1101    street_1
1102    street_2
1103    street_2
1104    street_2
1105    street_4
Name: Address, dtype: object

4. 多列索引

df.iloc[:,7::-2].head()
PhysicsWeightAddressClass
ID
1101A+63street_1C_1
1102B+73street_2C_1
1103B+82street_2C_1
1104B-81street_2C_1
1105B+64street_4C_1

5. 混合索引

df.iloc[3::4,7::-2].head()
PhysicsWeightAddressClass
ID
1104B-81street_2C_1
1203A+53street_6C_2
1302A-57street_1C_3
2101C84street_7C_1
2105A81street_4C_1

小节:由上所述,iloc中接收的参数只能为整数或整数列表,不能使用布尔索引

1.1.3、[] 操作符

1.1.3.1、Series的[]操作

1. 单元素索引

s = pd.Series(df['Math'],index = df.index)
s[1101]
34.0

2. 多行索引

s[0:4]
ID
1101    34.0
1102    32.5
1103    87.2
1104    80.4
Name: Math, dtype: float64

3. 函数式索引

s[lambda x : x.index[16::-6]]
ID
2102    50.6
1301    31.5
1105    84.8
Name: Math, dtype: float64

4. 布尔式索引

s[s>80]
ID
1103    87.2
1104    80.4
1105    84.8
1201    97.0
1302    87.7
1304    85.2
2101    83.3
2205    85.4
2304    95.5
Name: Math, dtype: float64
1.1.3.2、DataFrame的[]操作

1. 单行索引

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

2. 多行索引

df[3:5]
#用切片,如果是选取指定的某几行,推荐使用loc,否则很可能报错
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1104S_1C_1Fstreet_21678180.4B-
1105S_1C_1Fstreet_41596484.8B+
df.loc[1104:1105]
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1104S_1C_1Fstreet_21678180.4B-
1105S_1C_1Fstreet_41596484.8B+

3. 多列索引

df[['School','Math']].head()
SchoolMath
ID
1101S_134.0
1102S_132.5
1103S_187.2
1104S_180.4
1105S_184.8

4. 函数式索引

df[lambda x :['Math','Physics']].head()
MathPhysics
ID
110134.0A+
110232.5B+
110387.2B+
110480.4B-
110584.8B+
df[df['Gender'] == 'F'].head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1102S_1C_1Fstreet_21927332.5B+
1104S_1C_1Fstreet_21678180.4B-
1105S_1C_1Fstreet_41596484.8B+
1202S_1C_2Fstreet_41769463.5B-
1204S_1C_2Fstreet_51626333.8B
df[(df['Gender'] == 'F') & (df['Address'] == 'street_2')].head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1102S_1C_1Fstreet_21927332.5B+
1104S_1C_1Fstreet_21678180.4B-
2401S_2C_4Fstreet_21926245.3A
2404S_2C_4Fstreet_21608467.7B
df[(df['Math'] > 85) | (df['Address'] == 'street_7')].head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1103S_1C_1Mstreet_21868287.2B+
1201S_1C_2Mstreet_51886897.0A-
1302S_1C_3Fstreet_11755787.7A-
1303S_1C_3Mstreet_71888249.7B
1304S_1C_3Mstreet_21957085.2A
df[~((df['Math'] > 75) | (df['Address'] == 'street_1'))].head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1102S_1C_1Fstreet_21927332.5B+
1202S_1C_2Fstreet_41769463.5B-
1203S_1C_2Mstreet_61605358.8A+
1204S_1C_2Fstreet_51626333.8B
1205S_1C_2Fstreet_61676368.4B-
df.loc[df['Math']>60,(df[:8]['Address'] == 'street_6').values].head()
Physics
ID
1103B+
1104B-
1105B+
1201A-
1202B-
df[df['Address'].isin(['street_1','street_4']) & df['Physics'].isin(['A','A+'])]
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1101S_1C_1Mstreet_11736334.0A+
2105S_2C_1Mstreet_41708134.2A
2203S_2C_2Mstreet_41559173.8A+
df[df[['Address','Physics']].isin({'Address':['street_1','street_4'],'Physics':['A','A+']}).all(1)]
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1101S_1C_1Mstreet_11736334.0A+
2105S_2C_1Mstreet_41708134.2A
2203S_2C_2Mstreet_41559173.8A+
tuples = [('A','a'),('A','b'),('B','a'),('B','b')]
mul_index = pd.MultiIndex.from_tuples(tuples,names = ('Upper','Lower'))
mul_index
MultiIndex([('A', 'a'),
            ('A', 'b'),
            ('B', 'a'),
            ('B', 'b')],
           names=['Upper', 'Lower'])
pd.DataFrame({'Score':['perfect','good','fair','bad']},index = mul_index)
Score
UpperLower
Aaperfect
bgood
Bafair
bbad
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)
Score
UpperLower
Aaperfect
bgood
Bafair
bbad
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)
Score
UpperLower
Aaperfect
bgood
Bafair
bbad
mul_index
MultiIndex([('A', 'a'),
            ('A', 'b'),
            ('B', 'a'),
            ('B', 'b')],
           names=['Upper', 'Lower'])
L1 = ['A','B']
L2 = ['a','b']
pd.MultiIndex.from_product([L1,L2],names = ('Upper','Lower'))
MultiIndex([('A', 'a'),
            ('A', 'b'),
            ('B', 'a'),
            ('B', 'b')],
           names=['Upper', 'Lower'])
df_using_mul = df.set_index(['Class','Address'])
df_using_mul.head()
SchoolGenderHeightWeightMathPhysics
ClassAddress
C_1street_1S_1M1736334.0A+
street_2S_1F1927332.5B+
street_2S_1M1868287.2B+
street_2S_1F1678180.4B-
street_4S_1F1596484.8B+
df_using_mul.head()
SchoolGenderHeightWeightMathPhysics
ClassAddress
C_1street_1S_1M1736334.0A+
street_2S_1F1927332.5B+
street_2S_1M1868287.2B+
street_2S_1F1678180.4B-
street_4S_1F1596484.8B+
df_using_mul.sort_index().loc['C_2','street_5']
SchoolGenderHeightWeightMathPhysics
ClassAddress
C_2street_5S_1M1886897.0A-
street_5S_1F1626333.8B
street_5S_2M19310039.1B
df_using_mul.sort_index().loc[('C_2','street_6'):('C_3','street_4')]
SchoolGenderHeightWeightMathPhysics
ClassAddress
C_2street_6S_1M1605358.8A+
street_6S_1F1676368.4B-
street_7S_2F1947768.5B+
street_7S_2F1837685.4B
C_3street_1S_1F1755787.7A-
street_2S_1M1957085.2A
street_4S_1M1616831.5B+
street_4S_2F1577872.3B+
street_4S_2M1877348.9B
df_using_mul.sort_index().loc[('C_2','street_7'):'C_3'].head()
SchoolGenderHeightWeightMathPhysics
ClassAddress
C_2street_7S_2F1947768.5B+
street_7S_2F1837685.4B
C_3street_1S_1F1755787.7A-
street_2S_1M1957085.2A
street_4S_1M1616831.5B+
df_using_mul.sort_index().loc[[('C_2','street_7'),('C_3','street_6')]]
SchoolGenderHeightWeightMathPhysics
ClassAddress
C_2street_7S_2F1947768.5B+
street_7S_2F1837685.4B
C_3street_6S_2F1648195.5A-
df_using_mul.sort_index().loc[(['C_2','C_3'],['street_4','street_7']),:]
SchoolGenderHeightWeightMathPhysics
ClassAddress
C_2street_4S_1F1769463.5B-
street_4S_2M1559173.8A+
street_7S_2F1947768.5B+
street_7S_2F1837685.4B
C_3street_4S_1M1616831.5B+
street_4S_2F1577872.3B+
street_4S_2M1877348.9B
street_7S_1M1888249.7B
street_7S_2F1909965.9C

3. 多层索引中的slice对象

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
BigDEF
Smalldefdefdef
UpperLower
Aa0.1648460.2416330.0343360.7961220.4717220.5708250.6231440.9831680.375642
b0.8101880.3008580.1630510.3179530.5061540.2760520.7862760.5604130.134370
c0.0104430.4916510.6911160.8275310.1980970.5161770.9702330.9598320.146551
Ba0.7376420.6189270.2999630.4290470.1050240.3492130.7335880.9476790.398828
b0.6413420.4423210.3265630.7025570.7363360.2967210.2289180.5470850.313883
c0.7180830.5634240.3245850.6308630.7315560.5768710.2555300.4787720.909172
Ca0.7911730.9207240.5484370.9263310.8450070.1941060.5245240.3933350.974597
b0.4102580.1981710.9383700.1857030.8461970.1687320.2749200.1296500.758688
c0.4587520.9600050.0691760.1972600.3655880.2032710.4921560.5472110.506749

疑问,indexslice用法?

idx = pd.IndexSlice
df_s.loc[idx['B':,df_s['D']['d']>0.3],idx[df_s.sum()>4]]
BigDEF
Smalldededef
UpperLower
Ba0.7376420.6189270.4290470.1050240.7335880.9476790.398828
b0.6413420.4423210.7025570.7363360.2289180.5470850.313883
c0.7180830.5634240.6308630.7315560.2555300.4787720.909172
Ca0.7911730.9207240.9263310.8450070.5245240.3933350.974597
b0.4102580.1981710.1857030.8461970.2749200.1296500.758688
c0.4587520.9600050.1972600.3655880.4921560.5472110.506749

4. 索引层的交换

df_using_mul.head()
SchoolGenderHeightWeightMathPhysics
ClassAddress
C_1street_1S_1M1736334.0A+
street_2S_1F1927332.5B+
street_2S_1M1868287.2B+
street_2S_1F1678180.4B-
street_4S_1F1596484.8B+
df_using_mul.swaplevel(i=1,j=0,axis = 0).sort_index().head()
SchoolGenderHeightWeightMathPhysics
AddressClass
street_1C_1S_1M1736334.0A+
C_2S_2M1757447.2B-
C_3S_1F1755787.7A-
street_2C_1S_1F1927332.5B+
C_1S_1M1868287.2B+
df_muls = df.set_index(['School','Class','Address'])
df_muls.head()
GenderHeightWeightMathPhysics
SchoolClassAddress
S_1C_1street_1M1736334.0A+
street_2F1927332.5B+
street_2M1868287.2B+
street_2F1678180.4B-
street_4F1596484.8B+
df_muls.reorder_levels([2,0,1],axis = 0).sort_index().head()
GenderHeightWeightMathPhysics
AddressSchoolClass
street_1S_1C_1M1736334.0A+
C_3F1755787.7A-
S_2C_2M1757447.2B-
street_2S_1C_1F1927332.5B+
C_1M1868287.2B+
df_muls.reorder_levels(['Address','School','Class'],axis = 0).sort_index().head()
GenderHeightWeightMathPhysics
AddressSchoolClass
street_1S_1C_1M1736334.0A+
C_3F1755787.7A-
S_2C_2M1757447.2B-
street_2S_1C_1F1927332.5B+
C_1M1868287.2B+

三. 索引设定

3.1. index_loc参数设定

pd.read_csv('C:/Users/admin/Desktop/joyful-pandas-master/joyful-pandas-master/data/table.csv',index_col = ['Address','School']).head()
ClassIDGenderHeightWeightMathPhysics
AddressSchool
street_1S_1C_11101M1736334.0A+
street_2S_1C_11102F1927332.5B+
S_1C_11103M1868287.2B+
S_1C_11104F1678180.4B-
street_4S_1C_11105F1596484.8B+
df.head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1101S_1C_1Mstreet_11736334.0A+
1102S_1C_1Fstreet_21927332.5B+
1103S_1C_1Mstreet_21868287.2B+
1104S_1C_1Fstreet_21678180.4B-
1105S_1C_1Fstreet_41596484.8B+
df.reindex(index = [1101,1203,1206,2402])
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1101S_1C_1Mstreet_1173.063.034.0A+
1203S_1C_2Mstreet_6160.053.058.8A+
1206NaNNaNNaNNaNNaNNaNNaNNaN
2402S_2C_4Mstreet_7166.082.048.7B
df.reindex(columns=['Height','Gender','Average']).head()
HeightGenderAverage
ID
1101173MNaN
1102192FNaN
1103186MNaN
1104167FNaN
1105159FNaN
df.reindex(index = [1101,1203,1206,2402],method = 'bfill')
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1101S_1C_1Mstreet_11736334.0A+
1203S_1C_2Mstreet_61605358.8A+
1206S_1C_3Mstreet_41616831.5B+
2402S_2C_4Mstreet_71668248.7B
df.reindex(index = [1101,1203,1206,2402],method = 'nearest')
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1101S_1C_1Mstreet_11736334.0A+
1203S_1C_2Mstreet_61605358.8A+
1206S_1C_2Fstreet_61676368.4B-
2402S_2C_4Mstreet_71668248.7B
df_temp = pd.DataFrame({'Weight':np.zeros(5),
                        'Height':np.zeros(5),
                        'ID':[1101,1104,1103,1106,1102]}).set_index('ID')
df_temp.reindex_like(df[0:5][['Weight','Height']])
WeightHeight
ID
11010.00.0
11020.00.0
11030.00.0
11040.00.0
1105NaNNaN
df_temp1 = pd.DataFrame({'Weight':range(5),
                        'Height':range(5),
                        'ID':[1101,1104,1103,1106,1102]}).set_index('ID').sort_index()
df_temp1.reindex_like(df[0:5][['Weight','Height']],method='bfill')
WeightHeight
ID
110100
110244
110322
110411
110533
df.head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1101S_1C_1Mstreet_11736334.0A+
1102S_1C_1Fstreet_21927332.5B+
1103S_1C_1Mstreet_21868287.2B+
1104S_1C_1Fstreet_21678180.4B-
1105S_1C_1Fstreet_41596484.8B+
df.set_index('Class').head()
SchoolGenderAddressHeightWeightMathPhysics
Class
C_1S_1Mstreet_11736334.0A+
C_1S_1Fstreet_21927332.5B+
C_1S_1Mstreet_21868287.2B+
C_1S_1Fstreet_21678180.4B-
C_1S_1Fstreet_41596484.8B+
df.set_index('Class',append= True).head()
SchoolGenderAddressHeightWeightMathPhysics
IDClass
1101C_1S_1Mstreet_11736334.0A+
1102C_1S_1Fstreet_21927332.5B+
1103C_1S_1Mstreet_21868287.2B+
1104C_1S_1Fstreet_21678180.4B-
1105C_1S_1Fstreet_41596484.8B+
df.set_index(pd.Series(range(df.shape[0]))).head()
SchoolClassGenderAddressHeightWeightMathPhysics
0S_1C_1Mstreet_11736334.0A+
1S_1C_1Fstreet_21927332.5B+
2S_1C_1Mstreet_21868287.2B+
3S_1C_1Fstreet_21678180.4B-
4S_1C_1Fstreet_41596484.8B+
df.set_index([pd.Series(range(df.shape[0])),pd.Series(np.ones(df.shape[0]))]).head()
SchoolClassGenderAddressHeightWeightMathPhysics
01.0S_1C_1Mstreet_11736334.0A+
11.0S_1C_1Fstreet_21927332.5B+
21.0S_1C_1Mstreet_21868287.2B+
31.0S_1C_1Fstreet_21678180.4B-
41.0S_1C_1Fstreet_41596484.8B+
df.reset_index().head()
IDSchoolClassGenderAddressHeightWeightMathPhysics
01101S_1C_1Mstreet_11736334.0A+
11102S_1C_1Fstreet_21927332.5B+
21103S_1C_1Mstreet_21868287.2B+
31104S_1C_1Fstreet_21678180.4B-
41105S_1C_1Fstreet_41596484.8B+
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_temp = pd.DataFrame(np.random.rand(9,9),index=mul_index1,columns=mul_index2)
df_temp.head()
BigDEF
Smalldefdefdef
UpperLower
Aa0.2770610.2294050.7334550.2731640.1216250.6479500.9591010.5331450.485486
b0.8065940.8448240.3430620.4492540.5051030.6683660.4766970.0996370.130089
c0.0212760.0372260.5165420.8781640.8458350.3155550.5625460.9570170.571085
Ba0.8692120.7863850.8562680.7926810.4252810.7558750.4530190.3429790.610428
b0.6635810.5098400.4371870.8760600.5830250.5274390.4914030.8948460.520632

用level参数指定哪一层被reset,用col_level参数指定set到哪一层

df_temp1 = df_temp.reset_index(level = 1,col_level = 1)
df_temp1.head()
BigDEF
SmallLowerdefdefdef
Upper
Aa0.2770610.2294050.7334550.2731640.1216250.6479500.9591010.5331450.485486
Ab0.8065940.8448240.3430620.4492540.5051030.6683660.4766970.0996370.130089
Ac0.0212760.0372260.5165420.8781640.8458350.3155550.5625460.9570170.571085
Ba0.8692120.7863850.8562680.7926810.4252810.7558750.4530190.3429790.610428
Bb0.6635810.5098400.4371870.8760600.5830250.5274390.4914030.8948460.520632
df_temp1.columns
MultiIndex([( '', 'Lower'),
            ('D',     'd'),
            ('D',     'e'),
            ('D',     'f'),
            ('E',     'd'),
            ('E',     'e'),
            ('E',     'f'),
            ('F',     'd'),
            ('F',     'e'),
            ('F',     'f')],
           names=['Big', 'Small'])
df_temp1.index
Index(['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'], dtype='object', name='Upper')
df_temp.rename_axis(index = {'Lower':'Lower1'},columns={'Big':'Big1'})
Big1DEF
Smalldefdefdef
UpperLower1
Aa0.2770610.2294050.7334550.2731640.1216250.6479500.9591010.5331450.485486
b0.8065940.8448240.3430620.4492540.5051030.6683660.4766970.0996370.130089
c0.0212760.0372260.5165420.8781640.8458350.3155550.5625460.9570170.571085
Ba0.8692120.7863850.8562680.7926810.4252810.7558750.4530190.3429790.610428
b0.6635810.5098400.4371870.8760600.5830250.5274390.4914030.8948460.520632
c0.3970110.2032620.0919560.9769400.5654090.7106700.9907690.0542330.120749
Ca0.0803830.7063500.4569510.1913870.0283030.0020200.1233430.9403750.189775
b0.7027150.3945020.1571760.5689320.0795730.1359150.6816150.2096270.908920
c0.1106450.8753300.9890390.9664660.2490080.1920390.4740320.0689120.130035
df_temp.rename(index={'A':'T'},columns={'e':'e+'}).head()
BigDEF
Smallde+fde+fde+f
UpperLower
Ta0.2770610.2294050.7334550.2731640.1216250.6479500.9591010.5331450.485486
b0.8065940.8448240.3430620.4492540.5051030.6683660.4766970.0996370.130089
c0.0212760.0372260.5165420.8781640.8458350.3155550.5625460.9570170.571085
Ba0.8692120.7863850.8562680.7926810.4252810.7558750.4530190.3429790.610428
b0.6635810.5098400.4371870.8760600.5830250.5274390.4914030.8948460.520632

四、常用索引型函数

df.head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1101S_1C_1Mstreet_11736334.0A+
1102S_1C_1Fstreet_21927332.5B+
1103S_1C_1Mstreet_21868287.2B+
1104S_1C_1Fstreet_21678180.4B-
1105S_1C_1Fstreet_41596484.8B+
df.where(df['Gender']=='M').head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1101S_1C_1Mstreet_1173.063.034.0A+
1102NaNNaNNaNNaNNaNNaNNaNNaN
1103S_1C_1Mstreet_2186.082.087.2B+
1104NaNNaNNaNNaNNaNNaNNaNNaN
1105NaNNaNNaNNaNNaNNaNNaNNaN
df.where(df['Gender']=='M').dropna().head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1101S_1C_1Mstreet_1173.063.034.0A+
1103S_1C_1Mstreet_2186.082.087.2B+
1201S_1C_2Mstreet_5188.068.097.0A-
1203S_1C_2Mstreet_6160.053.058.8A+
1301S_1C_3Mstreet_4161.068.031.5B+
df.where(df["Gender"] == 'M',np.random.rand(df.shape[0],df.shape[1])).head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1101S_1C_1Mstreet_1173.00000063.00000034.000000A+
11020.3705220.8204460.9231730.9737140.8925040.3435640.1040430.360941
1103S_1C_1Mstreet_2186.00000082.00000087.200000B+
11040.1390490.7643160.9324790.1156840.4245600.0766950.8792970.0701079
11050.3457710.6234470.2458760.473490.4543280.8218990.2056520.20036
df.mask(df['Gender']=='M').dropna().head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1102S_1C_1Fstreet_2192.073.032.5B+
1104S_1C_1Fstreet_2167.081.080.4B-
1105S_1C_1Fstreet_4159.064.084.8B+
1202S_1C_2Fstreet_4176.094.063.5B-
1204S_1C_2Fstreet_5162.063.033.8B
df.mask(df["Gender"] == 'M',np.random.rand(df.shape[0],df.shape[1])).head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
11010.5134810.4214540.2944830.2150760.1894420.2942280.0716930.287266
1102S_1C_1Fstreet_2192.00000073.00000032.500000B+
11030.07123710.04094350.8884750.1973850.7929950.3507760.4541370.749055
1104S_1C_1Fstreet_2167.00000081.00000080.400000B-
1105S_1C_1Fstreet_4159.00000064.00000084.800000B+
df.head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1101S_1C_1Mstreet_11736334.0A+
1102S_1C_1Fstreet_21927332.5B+
1103S_1C_1Mstreet_21868287.2B+
1104S_1C_1Fstreet_21678180.4B-
1105S_1C_1Fstreet_41596484.8B+
df.query('Address in ["street_6","street_7"] & (Weight > (70+10)) & (ID in [1303,2304,2402])')
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1303S_1C_3Mstreet_71888249.7B
2304S_2C_3Fstreet_61648195.5A-
2402S_2C_4Mstreet_71668248.7B

五、重复元素处理

5.1、duplicated方法

该方法返回了是否重复的布尔列表

df.duplicated('Class').head()
ID
1101    False
1102     True
1103     True
1104     True
1105     True
dtype: bool

可选参数keep默认为first,即首次出现设为不重复,若为last,则最后一次设为不重复,若为False,则左右重复项为False.

df.duplicated('Class',keep='last').tail()
ID
2401     True
2402     True
2403     True
2404     True
2405    False
dtype: bool
df.duplicated('Class',keep = False).head()
ID
1101    True
1102    True
1103    True
1104    True
1105    True
dtype: bool

5.2、drop_duplicated方法

从名字上看即为剔除重复项

df.drop_duplicates('Class')
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1101S_1C_1Mstreet_11736334.0A+
1201S_1C_2Mstreet_51886897.0A-
1301S_1C_3Mstreet_41616831.5B+
2401S_2C_4Fstreet_21926245.3A
df.drop_duplicates('Class',keep='last')
SchoolClassGenderAddressHeightWeightMathPhysics
ID
2105S_2C_1Mstreet_41708134.2A
2205S_2C_2Fstreet_71837685.4B
2305S_2C_3Mstreet_41877348.9B
2405S_2C_4Fstreet_61935447.6B
  • 在传入多列时等价于将多列共同视作一个多级索引,比较重复项:
df.drop_duplicates(['School','Class'])
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1101S_1C_1Mstreet_11736334.0A+
1201S_1C_2Mstreet_51886897.0A-
1301S_1C_3Mstreet_41616831.5B+
2101S_2C_1Mstreet_71748483.3C
2201S_2C_2Mstreet_519310039.1B
2301S_2C_3Fstreet_41577872.3B+
2401S_2C_4Fstreet_21926245.3A

六、抽样函数

6.1、n为样本量

df.sample(n = 5)
SchoolClassGenderAddressHeightWeightMathPhysics
ID
2201S_2C_2Mstreet_519310039.1B
2304S_2C_3Fstreet_61648195.5A-
1205S_1C_2Fstreet_61676368.4B-
1304S_1C_3Mstreet_21957085.2A
1101S_1C_1Mstreet_11736334.0A+

6.2、frac为抽样比

df.sample(frac = 0.05)
SchoolClassGenderAddressHeightWeightMathPhysics
ID
2403S_2C_4Fstreet_61586059.7B+
1201S_1C_2Mstreet_51886897.0A-

6.3、replace为是否放回

df.sample(n =df.shape[0],replace = True).head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
2101S_2C_1Mstreet_71748483.3C
1104S_1C_1Fstreet_21678180.4B-
2105S_2C_1Mstreet_41708134.2A
1103S_1C_1Mstreet_21868287.2B+
1102S_1C_1Fstreet_21927332.5B+
df.sample(n=35,replace=True).index.is_unique
False

6.4、axis为抽样维度,默认为0,即抽行

df.sample(n=3,axis=1).head()
ClassWeightHeight
ID
1101C_163173
1102C_173192
1103C_182186
1104C_181167
1105C_164159

6.5、weights为样本权重,自动归一化

df.sample(n=3,weights=np.random.rand(df.shape[0])).head()
SchoolClassGenderAddressHeightWeightMathPhysics
ID
1201S_1C_2Mstreet_51886897.0A-
1303S_1C_3Mstreet_71888249.7B
2105S_2C_1Mstreet_41708134.2A

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值