广告
返回顶部
首页 > 资讯 > 后端开发 > Python >pandas 实现 in 和 not in 的用法及使用心得
  • 926
分享到

pandas 实现 in 和 not in 的用法及使用心得

pandas  in 和 not in 用法pandas  in 和 not in 2023-01-11 15:01:28 926人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

pandas in 和 not in 的用法 经常在处理数据中从一个总数据中清洗出数据, 但是有时候需要把没有处理的数据也统计出来. 这时候就需要使用: pandas.DataFra

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的,

到此这篇关于pandas 实现 in 和 not in 的用法及心得的文章就介绍到这了,更多相关pandas in 和 not in 的用法内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: pandas 实现 in 和 not in 的用法及使用心得

本文链接: https://www.lsjlt.com/news/177420.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作