使用标签时,开始和结束都包括在结果中。
import pandas as pd import numpy as np np.random.seed(5) df = pd.DataFrame(np.random.randint(100, size=(5, 5)), columns = list("ABCDE"), index = ["R" + str(i) for i in range(5)]) # Out: # A B C D E # R0 99 78 61 16 73 # R1 8 62 27 30 80 # R2 7 76 15 53 80 # R3 27 44 77 75 65 # R4 47 30 84 86 18
行R0到R2:
df.loc['R0':'R2'] # Out: # A B C D E # R0 9 41 62 1 82 # R1 16 78 5 58 0 # R2 80 4 36 51 27
请注意loc与iloc因为iloc不包括结束索引而有何不同
df.loc['R0':'R2'] # rows labelled R0, R1, R2 # Out: # A B C D E # R0 9 41 62 1 82 # R1 16 78 5 58 0 # R2 80 4 36 51 27 # df.iloc[0:2] # rows indexed by 0, 1 # A B C D E # R0 99 78 61 16 73 # R1 8 62 27 30 80
列C至E:
df.loc[:, 'C':'E'] # Out: # C D E # R0 62 1 82 # R1 5 58 0 # R2 36 51 27 # R3 68 38 83 # R4 7 30 62