pandas中的isin函数详解

今天有个同学问到,not in 的逻辑,想用 SQL 的select c_xxx_s from t1 left join t2 on t1.key=t2.key where t2.key is NULL 在 Python 中的逻辑来实现,实现了 left join 了(直接用join方法),但是不知道怎么实现where key is NULL。

其实,实现not in的逻辑,不用那么复杂,直接用isin函数再取反即可,下面就是isin函数的详解。

import pandas
df = pandas.DataFrame({
'A': [1, 2, 3],
'B': ['a', 'b', 'f']
})

如果是一个序列或者数组,
那么判断该位置的值,是否在整个序列或者数组中

df.isin(
[1, 3, 12, 'a']
)

A B
0 True True
1 False False
2 True False

df = pandas.DataFrame({
'A': [1, 2, 3],
'B': [1, 4, 7]
})

如果是一个dirt,
那么就会首先判断对应的index是否存在,
如果存在,那么就会判断对应的位置,在该列是否存在

df.isin({
'A': [1, 3],
'B': [4, 7, 12]
})

A B
0 True False
1 False True
2 True True

如果不存在,那么全部为False,例如B列没有,那么全部为False

df.isin({
'A': [1, 3],
'C': [4, 7, 12]
})

A B
0 True False
1 False False
2 True False

df = pandas.DataFrame({
'A': [1, 2, 3],
'B': ['a', 'b', 'f']
})
other = pandas.DataFrame({
'A': [1, 3, 3, 2],
'B': ['e', 'f', 'f', 'e']
})

如果是一个DataFrame,
首先就是列名要存在,
并且需要df中行列位置和B对应的行列位置一一匹配,才返回TRUE

df.isin(other)

A B
0 True False
1 False False
2 True True

other = pandas.DataFrame({
'C': [1, 3, 3, 2],
'D': ['e', 'f', 'f', 'e']
})

因为AB列皆不在,因此都为False<

df.isin(other)

A B
0 False False
1 False False
2 False False
嗯嗯?还没有讲到not in?哦哦,没有isnotin函数,取反的方法就是在函数前面加个 ~ ,好销魂的一飘。

~df.isin(other)
赞(0)
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权,转载请注明出处。
文章名称:《pandas中的isin函数详解》
文章来自:泰恩数据
文章链接:https://tyne.cc/739.html
本站资源仅供个人学习使用,请勿用于商业用途。

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址