loc:适合于列名索引
import numpy as np
import pandas as pd
df = pd. DataFrame( np. random. randn( 6 , 6 ) , columns= [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' ] )
print ( df)
"""
a b c d e f
0 -0.630324 1.066089 -1.914506 -0.357723 1.029126 1.270559
1 0.046037 -0.322757 -0.577944 -0.153088 1.476309 -0.818112
2 1.299177 0.836891 -0.734432 0.813605 0.042059 0.774934
3 1.799328 0.668888 -1.030505 -0.088439 0.156933 -0.074499
4 -0.627129 -0.641783 -1.110608 0.210518 1.091663 0.944219
5 -0.431648 -2.462586 0.263048 0.495652 0.256547 -0.453298
"""
print ( df. loc[ 1 : , [ 'f' ] ] )
"""
f
1 0.049556
2 2.134114
3 -0.807412
4 -0.041890
5 0.471554
"""
print ( df. loc[ 0 : 2 ] )
"""
a b c d e f
0 0.306412 -0.842496 -0.446566 -0.981444 -0.099904 1.698885
1 1.814793 -1.072987 0.662454 -0.645497 0.201988 -0.423346
2 -1.006800 -0.877562 0.407355 0.470193 0.560557 -0.210686
"""
print ( df. loc[ 0 : ] )
"""
a b c d e f
0 0.665126 -0.144586 -0.018197 -1.090340 -0.969164 -0.300332
1 -0.236940 0.185434 -1.258088 -0.153728 0.579723 1.281238
2 -0.674350 0.492838 -0.807699 -0.387080 0.148540 -0.374055
3 0.269290 0.798374 0.855519 1.906737 0.092352 0.140150
4 -0.294016 0.656729 -0.268822 1.191887 -0.050276 -0.304103
5 -0.484064 -0.487086 -1.504506 0.004128 -1.416468 -2.090432
"""
iloc:适合于位置索引
import numpy as np
import pandas as pd
df = pd. DataFrame( np. random. randn( 6 , 6 ) , columns= [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' ] )
print ( df)
"""
a b c d e f
0 -0.630324 1.066089 -1.914506 -0.357723 1.029126 1.270559
1 0.046037 -0.322757 -0.577944 -0.153088 1.476309 -0.818112
2 1.299177 0.836891 -0.734432 0.813605 0.042059 0.774934
3 1.799328 0.668888 -1.030505 -0.088439 0.156933 -0.074499
4 -0.627129 -0.641783 -1.110608 0.210518 1.091663 0.944219
5 -0.431648 -2.462586 0.263048 0.495652 0.256547 -0.453298
"""
print ( df. iloc[ 0 : 2 , 0 : 2 ] )
"""
a b
0 1.633693 1.043054
1 1.215390 0.460108
"""
print ( df. iloc[ 0 : ] )
"""
a b c d e f
0 1.001746 0.569914 0.600172 -1.717302 -0.187375 -0.136696
1 1.173294 0.622163 0.323354 1.257014 1.705656 0.114847
2 0.099195 1.589662 0.066309 -1.415009 0.184105 0.135455
3 0.024496 0.176972 2.819332 0.521369 1.114428 -0.641145
4 2.110000 2.806489 -0.176584 1.523781 -0.503577 -0.843958
5 1.548106 -1.355361 -1.367936 1.474386 0.426663 1.270759
"""
print ( df. iloc[ 2 : 3 , 2 : 4 ] )
"""
c d
2 0.085367 0.693742
"""