DataFrame 数据筛选
pandas DataFrame 數(shù)據(jù)篩選
- DataFrame 數(shù)據(jù)篩選
- 數(shù)據(jù)篩選基本格式
- contains
- isin
- 多個條件與或
- 數(shù)據(jù)篩選進階
- groupby
- agg
- np.where
DataFrame 數(shù)據(jù)篩選
近期使用pandas比較頻繁,在進行數(shù)據(jù)處理的時候經(jīng)常要用到dataframe的數(shù)據(jù)篩選功能,這里做個小結(jié)。
數(shù)據(jù)有以下的格式:
columns = [“blockNumber”,“timestamp”,“transactionHash”,“from”,“to”,“creates”,……“isError”]
數(shù)據(jù)篩選基本格式
初級篩選:
==, !=, >, >=, <, <=
主要用于簡單的判斷
contains
選取"from"列數(shù)據(jù),最后一位為0或a的數(shù)據(jù)。(數(shù)據(jù)類型默認str)
data[data['from'].str[-1:].str.contains('0|a')]contains語句中,可以以’|'符號為分割,添加多個候選項。
這里由于要只選最后一位,需要使用兩次 str 方法。
isin
已有一個取值數(shù)組,目標是選擇數(shù)據(jù)中,"from"數(shù)據(jù)的值在取值數(shù)組內(nèi)的數(shù)據(jù)
targetList = ['0x12','0x1a','0x98', ... , '0x82'] data[data['from'].isin(targetList)]這里targetList最好保持list的數(shù)據(jù)類型,使用pandas.Series可能會有意外的錯誤
反過來,如果目標是選擇數(shù)據(jù)中,"from"數(shù)據(jù)的值不在取值數(shù)組內(nèi)的數(shù)據(jù)
targetList = ['0x12','0x1a','0x98', ... , '0x82'] data[`data['from'].isin(targetList)]仔細注意,這里是在前面加個反引號 ` ,通過反引號來表示取反
多個條件與或
選取的是數(shù)據(jù)中,"from"列數(shù)據(jù)的取值在目標數(shù)組內(nèi),或者"to"列數(shù)據(jù)取值最后一位為0或a的數(shù)據(jù)
targetList = ['0x12','0x1a','0x98', ... , '0x82'] data[(data['from'].isin(targetList)) | (data['to'].str[-1:].str.contains('0|a'))]選取的是數(shù)據(jù)中,"from"列數(shù)據(jù)的取值在目標數(shù)組內(nèi),并且"to"列數(shù)據(jù)最后一位為0或a的數(shù)據(jù)
targetList = ['0x12','0x1a','0x98', ... , '0x82'] data[(data['from'].isin(targetList)) & (data['to'].str[-1:].str.contains('0|a'))]如果是多個條件并列在一起,每個條件都需要用括號括起來。
數(shù)據(jù)篩選進階
這里主要介紹一些,跟數(shù)據(jù)庫操作相似的數(shù)據(jù)篩選,假設數(shù)據(jù)格式如下:
columns = ['from', 'to', 'weight'] # from,to 都是 str數(shù)據(jù),weight是 int 數(shù)據(jù)groupby
這里,假設一個需求是,統(tǒng)計from中的值,出現(xiàn)的次數(shù),我們很容易想到可以通過value_counts() 方法直接獲取:
pd.DataFrame(data['from'].value_counts())這里value_counts()得到的是一個pandas.Series
那么更進一步,如果想知道"from"中的每個取值,對應的"to"取值跟"weight"取值分別是多少,可以使用:
agg
如果要統(tǒng)計的是 from 中的值,每個值對應的weight總和是多少,這時候需要使用到groupby跟agg
pd.DataFrame(data.groupby('from').agg('sum'))np.where
假設現(xiàn)在的需求是,將from跟to的數(shù)據(jù),每一行按照 from > to 的順序交換(注意不是整列交換)。這時可以使用np.where實現(xiàn)。
data['from'], data['to']= np.where(data['from'] > data['to'], [data['to'], data['from']], [data['from'], data['to']])np.where使用格式是:
np.where(condition, Yes, No)condition 為True時,取值為Yes,為False時,取值是No
總結(jié)
以上是生活随笔為你收集整理的DataFrame 数据筛选的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【计算机视觉】双目测距(二)--双目标定
- 下一篇: 忘记了电脑登陆密码,只记得PIN密码时可