Python 返回dataframe中的行,其中列中的元组包含特定值

Python 返回dataframe中的行,其中列中的元组包含特定值,python,pandas,tuples,dataframe,Python,Pandas,Tuples,Dataframe,我正在尝试查询pandas dataframe中的行,其中一列包含包含特定值的元组 例如: User Col1 0 1 (cat, dog, goat) 1 1 (cat, sheep) 2 1 (sheep, goat) 3 2 (cat, lion) 4 2 (fish, goat, lemur) 5 3 (cat, dog) 6

我正在尝试查询pandas dataframe中的行,其中一列包含包含特定值的元组

例如:

   User                 Col1
0     1     (cat, dog, goat)
1     1         (cat, sheep)
2     1        (sheep, goat)
3     2          (cat, lion)
4     2  (fish, goat, lemur)
5     3           (cat, dog)
6     4          (dog, goat)
7     4                  cat
因此,假设我想返回
Col1
包含“cat”的行,有没有一种方法可以在不遍历每一行并执行“if”(我的实际数据集有更多行)的情况下执行此操作


仅为最后一行返回“true”

为什么不将数据帧子集,然后输出其结果

catdf = df[df['Col1'].str.contains("cat")]

DataFrame列包含字符串和元组的混合体。我认为您无法避免重复该列。但是您可以使用apply方法高效地进行迭代。下面是示例代码

import pandas as pd

# fake data - in a Series for simplicity
tlist = [('cat', 'dog', 'goat'),
    ('cat', 'sheep'),
    ('sheep', 'goat'),
    ('cat', 'lion'),
    ('fish', 'goat', 'lemur'),
    ('cat', 'dog'),
    ('dog', 'goat'),
    'cat']
s = pd.Series(tlist)

# iterate Series with a lambda function searching for 'cat'
s.apply(lambda x: 'cat' in x)
这给了我以下输出

Out[38]: 
0     True
1     True
2    False
3     True
4    False
5     True
6    False
7     True
dtype: bool

您可以在以下范围内使用lambda函数:


当单元格中有
“cat”
时,lambda返回
True
。这对字符串(
“cat”
中的“cat”是
True
)和元组(
“cat”、“dog”)
中的“cat”是
True
)都有效。通过对
df
进行子集设置,可以得到lambda为
True

的所有行,这让我省去了很多焦虑。谢谢很高兴我能帮忙!
import pandas as pd

# fake data - in a Series for simplicity
tlist = [('cat', 'dog', 'goat'),
    ('cat', 'sheep'),
    ('sheep', 'goat'),
    ('cat', 'lion'),
    ('fish', 'goat', 'lemur'),
    ('cat', 'dog'),
    ('dog', 'goat'),
    'cat']
s = pd.Series(tlist)

# iterate Series with a lambda function searching for 'cat'
s.apply(lambda x: 'cat' in x)
Out[38]: 
0     True
1     True
2    False
3     True
4    False
5     True
6    False
7     True
dtype: bool
df[df["Col1"].apply(lambda x: True if "cat" in x else False)]