網站首頁 編程語言 正文
pandas in 和 not in 的用法
經常在處理數據中從一個總數據中清洗出數據, 但是有時候需要把沒有處理的數據也統計出來.
這時候就需要使用:
pandas.DataFrame.isin
DataFrame中的每個元素是否都包含在值中
pandas文檔位置
例子:
如何實現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實現in和 not in
pandas中經常會需要對某列做一些篩選,比如篩選某列里的不包含某些值的行,類似sql里的in和not in功能,那么怎么實現呢。
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']
那么想查看數據中是chines的,
df[df.country.isin(chinese)]
查看數據中不是chines的,
原文鏈接:https://ch3nnn.blog.csdn.net/article/details/91374033
相關推薦
- 2022-03-19 Docker之自定義網絡實現_docker
- 2022-11-18 redis批量操作pipeline管道操作方法_Redis
- 2022-11-02 用戶態和內核態-用戶線程和內核態線程的區別_其它相關
- 2022-04-12 安裝zsh&oh-my-zsh(沒有root權限)
- 2022-11-25 淺析Golang中的內存逃逸_Golang
- 2023-07-22 Spring的編程式事務TransactionTemplate
- 2022-07-31 Python常見的幾種數據加密方式_python
- 2022-03-21 .NET?6開發TodoList應用之實現ActionFilter_實用技巧
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支