Explanation of the difference between. loc and. iloc and. at and. iat in pandas
- 2021-10-24 23:22:02
- OfStack
Display index and implicit index
import pandas as pd
df = pd.DataFrame({' Name ':[' Zhang 3',' Li 4',' Wang 5'],' Achievement ':[85,59,76]})
Pass in a colon ':', which indicates all rows or columns
Display index:. loc, the first parameter is index slice, and the second parameter is columns column name
df.loc[2] #index For 2 Records of , This is the king 5 The results.
df.loc[:,' Name '] # No. 1 1 The parameters are colons, which indicate all rows. Here is the column record of Filter Name.
Implicit index:. iloc (integer_location), only integers can be passed in.
df.iloc[:2,:] # Zhang 3 And Lee 4 The achievement of , Slicing with list 1 Sample, colon closes left and opens right.
df.iloc[:,' Achievement '] # If you enter Chinese, you will report an error here, and you can only use integers.
You can also navigate to an element using at
Grammar rule: df. at [index, columns]
df.at[1,' Achievement '] # Using index tags, Lee 4 The achievement of
df.iat[1,1] # Similar to iloc Accessing an element using an implicit index
Supplement: pandas quickly locates all rows with a certain value in a 1 column, loc, at, = = comparison
As shown below:
goodDiskName2016
from datetime import datetime
from time import time
Position equal columns with direct square brackets
start = time()
for disk in goodDiskName2016[:100]:
____ST4000DM000_2016_good_feature27[ST4000DM000_2016_good_feature27.serial_number==disk][features27[0]]
time()-start
Time consumed
82.93997383117676
Direct loc positioning is equal
start = time()
for disk in goodDiskName2016[:100]: ____ST4000DM000_2016_good_feature27.loc[ST4000DM000_2016_good_feature27.serial_number==disk][features27[0]]
time()-start
Time elapsed:
82.4887466430664
First set this 1 column to index, and then find it through loc
df.loc[2] #index For 2 Records of , This is the king 5 The results.
df.loc[:,' Name '] # No. 1 1 The parameters are colons, which indicate all rows. Here is the column record of Filter Name.
0
df.loc[2] #index For 2 Records of , This is the king 5 The results.
df.loc[:,' Name '] # No. 1 1 The parameters are colons, which indicate all rows. Here is the column record of Filter Name.
1
Time elapsed:
df.loc[2] #index For 2 Records of , This is the king 5 The results.
df.loc[:,' Name '] # No. 1 1 The parameters are colons, which indicate all rows. Here is the column record of Filter Name.
2
Position with at after setting to index
start = time()
for disk in goodDiskName2016[:100]:
b.at[disk,features27[0]]
time()-start
Time elapsed:
df.loc[2] #index For 2 Records of , This is the king 5 The results.
df.loc[:,' Name '] # No. 1 1 The parameters are colons, which indicate all rows. Here is the column record of Filter Name.
4