gpt4 book ai didi

python - 删除不包含子字符串的行后如何返回数据框

转载 作者:行者123 更新时间:2023-11-30 21:53:19 25 4
gpt4 key购买 nike

我有一个很大的数据集,希望对其进行过滤以仅显示包含特定子字符串的行(在下面的示例中为“George”)(如果您告诉我如何传递多个子字符串,也会加分)

例如,如果我从代码开始

data = {
'Employee': ['George Brazil', 'Tim Swak', 'Rajesh Mahta', 'Kristy Karns', 'Jamie Hyneman', 'Pamela Voss', 'Tyrone Johnson', 'Anton Lafreu'],
'Director': ['Omay Wanja', 'Omay Wanja', 'George Stafford', 'Omay Wanja', 'George Stafford', 'Kristy Karns', 'Carissa Karns', 'Christie Karns'],
'Supervisor': ['George Foreman', 'Mary Christiemas', 'Omay Wanja', 'CEO PERSON', 'CEO PERSON', 'CEO PERSON', 'CEO PERSON', 'George of the jungle'],
'A series of ints to make this more complex': [1,0,1,4 , 1, 3, 3, 7]}
df = pd.DataFrame(data, index = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
df

Employee Director Supervisor A series of ints to make this more complex
a George Brazil Omay Wanja George Foreman 1
b Tim Swak Omay Wanja Mary Christiemas 0
c Rajesh Mahta George Stafford Omay Wanja 1
d Kristy Karns Omay Wanja CEO PERSON 4
e Jamie Hyneman George Stafford CEO PERSON 1
f Pamela Voss Kristy Karns CEO PERSON 3
g Tyrone Johnson Carissa Karns CEO PERSON 3
h Anton Lafreu Christie Karns George of the jungle 7

然后我想执行一个操作,使其返回数据帧,但仅包含行 a、c、e 和 h,因为它们是唯一包含子字符串“George”的行

最佳答案

试试这个

filters = 'George'
df[df.apply(lambda row: row.astype(str).str.contains(filters).any(), axis=1)]

编辑以返回子集

关于python - 删除不包含子字符串的行后如何返回数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59688781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com