比较元组没有问题
import pandas as pd
data = [
[1, (2,3,8)],
[2, (12,13,18)],
[3, (2,3,8)],
[4, (1,2,3,8,10)],
[5, (8,3,2)],
]
#----------------------------------------------
df_tuple = pd.DataFrame( data, columns=['a','b'])
print '\n DataFrame with tuples \n'
print df_tuple
print '\n tuple == : \n'
print df_tuple['b'] == (2,3,8)
print df_tuple[ df_tuple['b'] == (2,3,8) ]
print '\n tuple eq() : \n'
print df_tuple['b'].eq((2,3,8))
print df_tuple[ df_tuple['b'].eq((2,3,8)) ]
#----------------------------------------------
结果
DataFrame with tuples
a b
0 1 (2, 3, 8)
1 2 (12, 13, 18)
2 3 (2, 3, 8)
3 4 (1, 2, 3, 8, 10)
4 5 (8, 3, 2)
tuple == :
0 True
1 False
2 True
3 False
4 False
Name: b, dtype: bool
a b
0 1 (2, 3, 8)
2 3 (2, 3, 8)
tuple eq() :
0 True
1 False
2 True
3 False
4 False
Name: b, dtype: bool
a b
0 1 (2, 3, 8)
2 3 (2, 3, 8)
但是比较列表存在问题,我不知道为什么。
但是您需要包含列表 [2,3,8] 中所有或多个项目的行,所以我会使用 apply() 和自己的函数。
import pandas as pd
#----------------------------------------------
data = [
[1, [2,3,8]],
[2, [12,13,18]],
[3, [2,3,8]],
[4, [1,2,3,8,10]],
[5, [8,3,2]],
]
#----------------------------------------------
df_list = pd.DataFrame( data, columns=['a','b'])
print '\n DataFrame with lists \n'
print df_list
print '\n test: \n'
# test if any element from data list is in [2,3,8]
def test(data):
return any( x in [2,3,8] for x in data )
print df_list['b'].apply(test)
print df_list[ df_list['b'].apply(test) ]
#----------------------------------------------
结果
DataFrame with lists
a b
0 1 [2, 3, 8]
1 2 [12, 13, 18]
2 3 [2, 3, 8]
3 4 [1, 2, 3, 8, 10]
4 5 [8, 3, 2]
test:
0 True
1 False
2 True
3 True
4 True
Name: b, dtype: bool
a b
0 1 [2, 3, 8]
2 3 [2, 3, 8]
3 4 [1, 2, 3, 8, 10]
4 5 [8, 3, 2]
更有用的版本 - 带有第二个参数:
test_any return True 如果 data 列表中的 any 元素在 expected 列表中
def test_any(data, expected):
return any( x in expected for x in data )
print df_list['b'].apply(lambda x:test_any(x,[2,3,8]) )
print df_list[ df_list['b'].apply(lambda x:test_any(x,[2,3,8]) ) ]
test_all return True 如果数据列表中的所有元素都在预期列表中
def test_all(data, expected):
return all( x in expected for x in data )
print df_list['b'].apply(lambda x:test_all(x,[2,3,8]) )
print df_list[ df_list['b'].apply(lambda x:test_all(x,[2,3,8]) ) ]
你可以交换'x'和[2,3,8]
如果预期列表中的任何元素在数据列表中
,则获取
True
print df_list[ df_list['b'].apply(lambda x:test_any_2([2,3,8], x) ) ]
如果预期列表中的所有元素都在数据列表中
,则获取
True
print df_list[ df_list['b'].apply(lambda x:test_all_2([2,3,8], x) ) ]