[每日一答] [20151015] pandas中的isin函数详解

来源:互联网 发布:unity3d免费模型 编辑:程序博客网 时间:2024/04/27 21:19


今天有个同学问到一个逻辑,就是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)


今天有个同学问到一个逻辑,就是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 1