pandas 数据框列中的成员资格测试

rah*_*ram 5 python membership contains list pandas

我有一个 Pandas 数据框,它的一列是一个列表。请参阅以下内容:

>>> 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]
Run Code Online (Sandbox Code Playgroud)

我想在 C2 中找到包含 6 的行并返回 C1 中的值。我想过类似的事情

b = a["C1"][(6 in a["C2"])]
return(int(b))
Run Code Online (Sandbox Code Playgroud)

但它不起作用。谢谢。

jez*_*ael 4

我认为您需要applyin测试list创建的价值boolean mask

print (a.C2.apply(lambda x: 6 in x))
0    False
1    False
2    False
3     True
Name: C2, dtype: bool
Run Code Online (Sandbox Code Playgroud)

然后使用locwith boolean indexingfor select by mask

b = a.loc[a.C2.apply(lambda x: 6 in x), 'C1']
print (b)
3    19
Name: C1, dtype: int64
Run Code Online (Sandbox Code Playgroud)

最后如果需要标量输出转换为numpy array并选择第一个值[]

print (b.values)
[19]

print (b.values[0])
19
Run Code Online (Sandbox Code Playgroud)

或者使用iatiloc

print (b.iat[0])
19

print (b.iloc[0])
19
Run Code Online (Sandbox Code Playgroud)