1. 程式人生 > >[Pandas]資料選取/資料切片

[Pandas]資料選取/資料切片

在對資料做相應操作之前,我們要先篩選出所需的資料,pandas提供了一些方法方便我們選取資料,這裡主要講解dataFrame型別的資料選取,Series型別用法類似,可以查閱文件中的相關屬性。

pandas主要提供了三種屬性用來選取行/列資料:

屬性名 屬性
ix 根據整數索引或者行標籤選取資料
iloc 根據位置的整數索引選取資料
loc 根據行標籤選取資料

在 0.20.0版本不支援ix這種混合選取的方法

這三種屬性,既可以讓我們獲取整行/整列的資料,也可以讓我們選取符合標準的行/列資料。下面舉一些小例子來說明,更加豐富的例子可以看參考資料中*[pandas 0.23.4 documentation —— Indexing and Selecting Data]*

1. iloc

df.iloc[引數]

iloc提供了五種引數形式

input example output
整數(行索引) df.iloc[5] 選取第6行資料
整數陣列 df.iloc[[1,3,5]] 選取第2,4,6行資料
整數切片 df.iloc[1:3] 選取2~4行資料(不包含第4行資料)
布林值陣列 df.iloc[[True,False,True] 選取第1,3行資料
函式 df.iloc[(df[‘one’]>10).tolist()] 選取’one’這列大於10的那一行資料

注意:iloc接受有返回值的函式作為引數,但要保證函式返回的是整數/整數list

布林值/布林list

如果直接執行 df.iloc[df[‘one’]>10]

則會報錯 NotImplementedError: iLocation based boolean indexing on an integer type is not available

因為df[‘one’] > 10 返回的是 series型別的資料

除此之外,還可以進行組合切片

input example output
整數(行索引) df.iloc[5,1] 選取第6行,第2列的資料
整數陣列 df.iloc[[1,3],[1,2]] 選取第2,4行;2,3列的資料
整數切片 df.iloc[1:3,1:3] 選取第2,3行;2,3列的資料
布林值陣列 df.iloc[[True,True,False],[True,False,True]] 選取第1,2行;1,3列的資料

要注意的是,我們用df[引數]也可以進行切片,但這種方式容易引起chained indexing 問題。除此之外,**df[lable1][lable2]**的操作是線性的,對lable2的選取是在df[lable1]的基礎上進行,速度相對較慢。所以在對資料進行切片的時候儘量使用iloc這類的方法

2. loc

loc也提供了五種引數形式

input example(摘自官方文件) output
行標籤 df.loc[‘viper’] 選取viper那一行
行標籤陣列 df.loc[[‘viper’, ‘sidewinder’]] 選取行標籤為viper、sidewinder
行標籤切片 df.loc[‘cobra’:‘viper’, ‘max_speed’] 選取從cobra到viper行的max_speed列
布林值陣列 df.loc[[False, False, True]]
函式 df.loc[df[‘shield’] > 6, [‘max_speed’]] 選取shield列大於6的那一行的max_speed資料

注意 df.loc[df[‘one’]>10]這樣的寫法是可以正常選出one列大於10的資料

3. ix

ix支援基於混合整數和標籤的訪問,它支援.loc和iloc的任何輸入,還支援浮點標籤。

4. values

df.values

執行該屬性,會將DataFrame中資料以ndarray的型別返回回來, 所以我們在此基礎上利用索引選取相應的行資料

df = pd.read_excel('test.xlsx')
print(df)

結果
在這裡插入圖片描述

print(df.values)

結果
在這裡插入圖片描述

print(df.values[1]) #選取第2行的資料

結果
在這裡插入圖片描述

5. at

訪問行/列標籤對的單個值。

6. iat

按整數位置訪問行/列對的單個值。

參考資料

[pandas 0.23.4 documentation —— Indexing and Selecting Data]

http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-integer

[pandas 0.23.4 documentation —— DataFrame ]

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html

[部落格: pandas中Dataframe的查詢方法([], loc, iloc, at, iat, ix)]

https://blog.csdn.net/wr339988/article/details/65446138

[pandas 0.23.4 documentation —— Returning a view versus a copy]

http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

[stack overflow —— pandas iloc vs ix vs loc explanation, how are they different?]

https://stackoverflow.com/questions/31593201/pandas-iloc-vs-ix-vs-loc-explanation-how-are-they-different

[stack overflow —— When to use iloc and loc for boolean]

https://stackoverflow.com/questions/51585502/when-to-use-iloc-and-loc-for-boolean