定位行:.iloc[] 与 .loc[]

使用 pandas 编写高效代码

Leonidas Souliotis

PhD Candidate

扑克牌数据集

S1 R1 S2 R2 S3 R3 S4 R4 S5 R5
1 10 Jack King 4 Ace
2 Jack King 10 Queen Ace
3 Queen Jack King 10 Ace
S1 R1 S2 R2 S3 R3 S4 R4 S5 R5
1 2 10 3 11 3 13 4 4 1 1
2 2 11 2 13 2 10 2 12 2 1
3 3 12 3 11 3 13 3 10 3 1

Sn:第 n 张牌的花色

1(红桃)、2(方块)、3(梅花)、4(黑桃)

Rn:第 n 张牌的点数

1(A)、2-10、11(J)、12(Q)、13(K)

使用 pandas 编写高效代码

定位目标行

.loc[] — 按索引标签定位

# 指定要选择的行范围
rows = range(0, 500)
# 计时使用 .loc[] 选取行
loc_start_time = time.time()
data.loc[rows]    
loc_end_time = time.time()

print("Time using .loc[] : {} sec".format(
            loc_end_time - loc_start_time))
Time using .loc[]: 0.001951932 seconds

.iloc[] — 按位置索引定位

# 指定要选择的行范围
rows = range(0, 500)
# 计时使用 .iloc[] 选取行
iloc_start_time = time.time()
data.iloc[rows]    
iloc_end_time = time.time()

print("Time using .iloc[]: {} sec".format(
            iloc_end_time - iloc_start_time)
Time using .iloc[] : 0.0007140636 sec
Difference in speed: 173.355592654%
使用 pandas 编写高效代码

定位目标列

.iloc[] — 按位置索引定位

iloc_start_time = time.time()
data.iloc[:,:3]
iloc_end_time = time.time()
print("Time using .iloc[]: {} sec".format(
            iloc_end_time - iloc_start_time))
Time using .iloc[]: 0.00125193595886 sec

按列名定位

names_start_time = time.time()
data[['S1', 'R1', 'S2']]
names_end_time = time.time()
print("Time using selection by name: {} sec".format(
            names_end_time - names_start_time))
Time using selection by name: 0.000964879989624 sec
Difference in speed: 29.7504324188%
使用 pandas 编写高效代码

开始练习!

使用 pandas 编写高效代码

Preparing Video For Download...