欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

pandas?實現(xiàn)?in?和?not?in?的用法及使用心得

 更新時間:2023年01月11日 14:35:32   作者:Ch3n  
pandas按條件篩選數(shù)據(jù)時,除了使用query()方法,還可以使用isin和對isin取反進行條件篩選,今天通過本文給大家介紹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中的每個元素是否都包含在值中

pandas文檔位置

例子:

如何實現(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)文章

最新評論