更新時間:2023-11-03 來源:黑馬程序員 瀏覽量:
pandas中提供了多種使用單層索引訪問Series類對象和DataFrame類對象的方式,包括[]、loe、iloc、at和iat,關(guān)于這幾種方式的介紹如下。
pandas中使用[]訪問數(shù)據(jù)的方式與訪問數(shù)組元素的方式類似,其使用方式如下。
變量{索引}
需要說明的是,若變量是一個Series類對象,則會獲取索引對應(yīng)的單個數(shù)據(jù);若變量是一個DataFrame類對象,它在使用“[索引J”訪問數(shù)據(jù)時會將索引視為列索引,獲取該索引對應(yīng)的一列數(shù)據(jù)。
下面創(chuàng)建一個Series類對象ser,使用“變量[索引]”訪問該對象的單個數(shù)據(jù),代碼如下。
In []: inport pandas as pd
ser = pd.Series(['A', 'B','C','D'],
index=('one','two','three',*four'])
print(ser)
one A
two B
three C
four D
dtype: object
In []: # 訪問素引為'one'的數(shù)據(jù)
print(ser['one'])
A
下面創(chuàng)建一個DataFrame類對象df,使用“變量[索引]”訪問該對象的一列數(shù)據(jù),代碼如下。
In []: df = pd.DataF'rame([[0, 2, 3], [0, 4, 1], [10, 20, 30]],
index=|4, 5, 6], columns=['A', 'B', 'C'])
print(df)
A B C
4 0 2 3
5 0 4 3
6 10 20 30
In []: # 訪問列索引為'A'的數(shù)據(jù)
print(df['A'])
4 O
5 0
6 10
Name: A, dtype: int64
pandas 中也可以使用loc和iloc訪問數(shù)據(jù),其使用方式如下。
變量.loc[索引]
變量.iloc[索引]
以上方式中,“l(fā)od[索引]”中的索引必須為自定義的標簽索引,而“ilocf[索引]”中的索引必須為自動生成的整數(shù)索引。需要說明的是,若變量是一個DataFrame類對象,它在使用“l(fā)oc[索引]”或“iloc[索引]”訪問數(shù)據(jù)時會將索引視為行索引,獲取該索引對應(yīng)的一行數(shù)據(jù)。
接下來,分別使用loc和iloc訪問ser對象中標簽索引為'two'與整數(shù)索引為2的數(shù)據(jù),代碼如下。
In []: # 訪問標簽索引為'two'的數(shù)據(jù)
print(ser.loc('two'))
B
In []: 訪問整數(shù)索引為2的數(shù)據(jù)
print(ser.1loc[2))
C
使用loc和iloc訪問df對象中標簽索引為4和整數(shù)索引為1的數(shù)據(jù),代碼如下。
In []: # 訪問標簽索引為4的數(shù)據(jù)
print(df.loc(4])
A 0
B 2
C 3
Name: 4, dtype: int64
In []: # 訪問整數(shù)索引為1的數(shù)據(jù)
print(df.iloc[1])
A 0
B 4
C 1
Name: 5, dtype: int64
pandas 中還可以使用at和iat 訪問數(shù)據(jù)。與前兩種方式相比,這種方式可以訪問DataFrame類對象中的單個數(shù)據(jù)。以DataFrame類對象為例,使用at和iat 訪問數(shù)據(jù)的基本方式如下。
變量.at[行素引,列索引1
變量,iat[行素引,列索引]
以上方式中,“at[行索引,列索引]”中的索引必須為自定義的標簽索引,“iat[行索引,列索引]”中的索引必須為自動生成的整數(shù)索引。
接下來,使用at訪問d對象中行標簽索引為5、列標簽索引為B'的數(shù)據(jù),代碼如下。
In []: # 訪問行標簽索引為5、列標簽索引為'8'的數(shù)據(jù)
print(df.at[5,'B'])
4