pandas 数据框架列中的成员资格测试 [英] membership test in pandas data frame column
本文介绍了 pandas 数据框架列中的成员资格测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个熊猫数据框,其中的一列是列表.请参见以下内容:
I have a pandas data frame that one of its columns is a list. Please see below:
>>> a.head
C1 C2
0 23 [2,4,5,8,1]
1 24 [1,2]
2 15 [-2]
3 19 [1,3,4,5,6,7,8,9,0]
我想在C2中找到一个包含6的行,并在C1中返回该值.我想到了类似的东西
I would like to find a row that contains 6 in the C2 and return the value in C1. I thought for something like
b = a["C1"][(6 in a["C2"])]
return(int(b))
,但是它不起作用.谢谢.
but it is not working. Thanks.
推荐答案
我认为您需要 apply
和 in
中的 list
中的测试值用于创建布尔掩码
:
I think you need apply
and in
for test value in list
for creating boolean mask
:
print (a.C2.apply(lambda x: 6 in x))
0 False
1 False
2 False
3 True
Name: C2, dtype: bool
然后使用 loc
与 布尔索引
> 用于通过 mask
选择:
b = a.loc[a.C2.apply(lambda x: 6 in x), 'C1']
print (b)
3 19
Name: C1, dtype: int64
如果需要标量输出,最后将其转换为 numpy数组
并通过 []
选择第一个值:
Last if need scalar output convert to numpy array
and select first value by []
:
print (b.values)
[19]
print (b.values[0])
19
print (b.iat[0])
19
print (b.iloc[0])
19
这篇关于 pandas 数据框架列中的成员资格测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文