[每日一答] [20151015] 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)


今天有個同學問到一個邏輯,就是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)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章