pandas?實現(xiàn)?in?和?not?in?的用法及使用心得
pandas in 和 not in 的用法
經(jīng)常在處理數(shù)據(jù)中從一個總數(shù)據(jù)中清洗出數(shù)據(jù), 但是有時候需要把沒有處理的數(shù)據(jù)也統(tǒng)計出來.
這時候就需要使用:
pandas.DataFrame.isin
DataFrame中的每個元素是否都包含在值中
例子:
如何實現(xiàn)SQL的等價物IN和NOT IN? 我有一個包含所需值的列表。下面是一個場景: df = pd.DataFrame({'countries':['US','UK','Germany','China']}) countries = ['UK','China'] # pseudo-code: df[df['countries'] not in countries]
之前的做法是這樣:
df = pd.DataFrame({'countries':['US','UK','Germany','China']}) countries = pd.DataFrame({'countries':['UK','China'], 'matched':True}) # IN df.merge(countries,how='inner',on='countries') # NOT IN not_in = df.merge(countries,how='left',on='countries') not_in = not_in[pd.isnull(not_in['matched'])]
但上面這樣做覺得很不好, 也翻了文檔才找到比較好解決方式.
# IN something.isin(somewhere) # NOT IN ~something.isin(somewhere)
例子:
>>> df countries 0 US 1 UK 2 Germany 3 China >>> countries ['UK', 'China'] >>> df.countries.isin(countries) 0 False 1 True 2 False 3 True Name: countries, dtype: bool >>> df[df.countries.isin(countries)] countries 1 UK 3 China >>> df[~df.countries.isin(countries)] countries 0 US 2 Germany
ps:pandas實現(xiàn)in和 not in
pandas中經(jīng)常會需要對某列做一些篩選,比如篩選某列里的不包含某些值的行,類似sql里的in和not in功能,那么怎么實現(xiàn)呢。
import pandas as pd columns = ['name','country'] index = [1,2,3,4] row1 = ['a','China'] row2 = ['b','UK'] row3 = ['c','USA'] row4 = ['d','HK'] df = pd.DataFrame([row1,row2,row3,row4], index=index, columns=columns) df chinese = ['China','HK']
那么想查看數(shù)據(jù)中是chines的,
df[df.country.isin(chinese)]
查看數(shù)據(jù)中不是chines的,
到此這篇關(guān)于pandas 實現(xiàn) in 和 not in 的用法及心得的文章就介紹到這了,更多相關(guān)pandas in 和 not in 的用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python輕松辦公將100個Excel中符合條件的數(shù)據(jù)匯總到1個Excel里
這篇文章主要為大家介紹了python輕松辦公將100個Excel中符合條件的數(shù)據(jù)匯總到1個Excel里示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03PyQt5?python?數(shù)據(jù)庫?表格動態(tài)增刪改詳情
這篇文章主要介紹了PyQt5?python?數(shù)據(jù)庫?表格動態(tài)增刪改詳情,首先手動連接數(shù)據(jù)庫與下一個的程序連接數(shù)據(jù)庫是獨立的2個部分,下面來看看文章的詳細介紹2022-01-01Python的Twisted框架上手前所必須了解的異步編程思想
Twisted是Python世界中人氣最高的framework之一,異步的工作模式使其名揚天下,這里為大家總結(jié)了Python的Twisted框架上手前所必須了解的異步編程思想,需要的朋友可以參考下2016-05-05如何使用python的ctypes調(diào)用醫(yī)保中心的dll動態(tài)庫下載醫(yī)保中心的賬單
這篇文章主要介紹了如何使用python的ctypes調(diào)用醫(yī)保中心的dll動態(tài)庫下載醫(yī)保中心的賬單,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05Python統(tǒng)計列表元素出現(xiàn)次數(shù)的方法示例
這篇文章主要介紹了Python統(tǒng)計列表元素出現(xiàn)次數(shù)的方法示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-04-04