检查特定值是否在数据框的某列中

2 投票
2 回答
43 浏览
提问于 2025-04-14 16:48

我刚开始学习Python,试着使用下面的代码:

pos = pd.DataFrame(columns=['id', 'pred'])
pos.loc[1,'id'] = [4, 4, 4]
pos.loc[2,'id'] = [2, 3, 3]
list1 = [2, 3, 3]
list2 = [3, 2, 3]
print(pos)
print(list1 in pos['id'].values)
print(list2 in pos['id'].values)

结果出现了这个错误:

ValueError: 操作数的形状不匹配,无法一起处理,形状分别是 (2,) 和 (3,)

2 个回答

0

使用 to_list 方法可以把数据转换成一个 Python 对象,而不是一个 numpy 数组:

list1 in pos['id'].to_list()
# True

list2 in pos['id'].tolist()
# False

中间步骤:

pos['id'].tolist()
# [[4, 4, 4], [2, 3, 3]]
1

你可以使用 any() 这个函数:

list1 = [2, 3, 3]
list2 = [3, 2, 3]

print(any(l == list1 for l in pos["id"]))
print(any(l == list2 for l in pos["id"]))

输出结果是:

True
False

撰写回答