pandas中對DataFrame篩選數據的方法有很多的,以后會后續進行補充,這里只整理遇到錯誤的情況。
1.使用布爾型DataFrame對數據進行篩選
使用一個條件對數據進行篩選,代碼類似如下:
num_red=flags[flags['red']==1]
使用多個條件對數據進行篩選,代碼類似如下:
不同的條件用()包裹起來,並或非分別使用&,|,~而非and,or,not
stripes_or_bars=flags[(flags['stripes']>=1) | (flags['bars']>=1)]
常見的錯誤代碼如下:
代碼一:
條件沒用(),或沒有使用|
stripes_or_bars=flags[flags['stripes']>=1 or flags['bars']>=1]
代碼二:
沒有使用()
stripes_or_bars=flags[flags['stripes']>=1 | flags['bars']>=1].
代碼三:
或沒用用|
stripes_or_bars=flags[(flags['stripes']>=1) or (flags['bars']>=1)]
以上這三種代碼的錯誤提示都是:ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 中括號里面的邏輯式如何解析的暫時不清楚。貌似不能使用and、or及not。
除了使用組合的邏輯表達式之外,使用返回類型為布爾型值的函數也可以達到篩選數據的效果。示例如下:
import pandas as pdimport numpy as npdf=pd.DataFrame(np.array(range(10)).reshape((5,-1)))df.columns=['0','1']df=df[df['1'].isin([3,5,9])]
其df的結果如下:
2.iloc()方法和iloc()方法的區別
首先dataframe一般有兩種類型的索引:第一種是位置索引,即dataframe自帶的從0開始的索引,這種索引叫位置索引。另一種即標簽索引,這種索引是你在創建datafram時通過index關鍵字,或者通過其他index相關方法重新給dataframe設置的索引。這兩種索引是同時存在的。一般設置了標簽索引之后,就不在顯示位置索引,但不意味着位置索引就不存在了。
假設有如下幾行數據(截圖部分只是數據的一部分),很明顯,以下顯示的索引為標簽索引。同時574(標簽索引)行對應的位置索引則為0,1593行對應的位置索引為2, 以此類推。
先來看loc(),其API網址http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.htm,函數名下方有一行解釋,Access a group of rows and columns by label(s) or a boolean array.. loc[] is primarily label based, but may also be used with a boolean array.
代碼一:
first_listing = normalized_listings.loc[[0,4]]
結果如下,可以看出其輸出的是dataframe中標簽索引為0和4的兩行數據。注意,如果標簽索引的類型為字符串,則在loc中也要用字符串的形式。
再來看iloc(),其API網址http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html,函數名下方的解釋為 Purely integer-location based indexing for selection by position. .iloc[] is primarily integer position based ( from 0 to length-1 of the axis), but may also be used with a boolean array.
代碼二:
first_listing = normalized_listings.iloc[[0,4]]
結果如下,可以看出其輸出的dataframe中第0行和第4行的數據,即按方法是按照位置索引取得數。注意使用位置索引的時候只能用整數(integer position,bool類型除外)
另外,還可以向loc和iloc中傳入bool序列,這樣就可以將前面介紹的boo表達式用到loc和iloc中。下面來看看怎么使用bool序列?
import pandas as pddata=pd.DataFrame(data={'col1':[1,2,3,5,10],'col2':[50,90,67,75,100]},\ index=['a','b','c','d','e'])
print(data)
#iloc[]示例,iloc似乎不能直接使用邏輯表達式的結果,我這里將其轉置成list之后就可以用了,原因暫且不明data_1=data.iloc[list(data['col1']>5)]
print(data_1)
#loc[]示例,loc中可以直接使用邏輯表達式data_2=data.loc[data['col1']>5]
print(data_2)
在iloc[]中,如果直接使用loc中的邏輯表達式而不進行list()轉化的話,會提示ValueError: iLocation based boolean indexing cannot use an indexable as a mask錯誤。
如果查看上述兩段代碼中得到的first_listing。我們會發現兩處first_listing的類型均為datafrarm。loc和iloc除了能對行進行篩選,還可以篩選列。如果在loc和iloc中設定了對列的篩選,則篩選之后得到的數據可能是datafrme類型,也有可能是Series類型。下面直接以代碼運行結果進行說明。
import pandas as pddata=pd.DataFrame(data={'col1':[1,2,3,5,10],'col2':[50,90,67,75,100]},\ index=['a','b','c','d','e'])
print(data)
#iloc[]示例 ,在使用iloc的時候,[]里面無論是篩選行還是篩選列,都只能使用數字形式的行號或列號。#這里如果使用‘col2',這里會報錯data_1=data.iloc[[0,4],[1]]#當需要篩選出多列或者希望返回的結果為DataFrame時,可以將列號用[]括起來。
print(data_1)
print(type(data_1))
data_2=data.iloc[[0,4],1]
#當只需要篩選出其中的一列時可以只寫一個列號,不加中括號,這種方法得到的是一個Seriesprint(data_2)print(type(data_2))
#loc[]示例
data_3=data.loc[['a','e'],['col2']]
print(data_3)
print(type(data_3))
data_4=data.loc[['a','e'],'col2']
print(data_4)
print(type(data_4))
具體的代碼執行結果如下: