Python 基于列表对数据帧中的行进行灰显
我有以下数据框:Python 基于列表对数据帧中的行进行灰显,python,pandas,Python,Pandas,我有以下数据框: ProbeGenes sample1 sample2 sample3 0 1431492_at Lipn 20.3 130 1 1 1448678_at Fam118a 25.3 150 2 2 1452580_a_at Mrpl21 3.1 173 12 它是使用以下代码创建的: import pandas as pd df = pd
ProbeGenes sample1 sample2 sample3
0 1431492_at Lipn 20.3 130 1
1 1448678_at Fam118a 25.3 150 2
2 1452580_a_at Mrpl21 3.1 173 12
它是使用以下代码创建的:
import pandas as pd
df = pd.DataFrame({'ProbeGenes' : ['1431492_at Lipn', '1448678_at Fam118a','1452580_a_at Mrpl21'],
'sample1' : [20.3, 25.3,3.1],
'sample2' : [130, 150,173],
'sample3' : [1.0, 2.0,12.0],
})
然后,我想做的是列出一个清单:
list_to_grep = ["Mrpl21","lipn","XXX"]
我想提取(grep)df
子集,其中ProbeGenes
列成员包含在list_to_grep
中,产生:
ProbeGenes sample1 sample2 sample3
1431492_at Lipn 20.3 130 1
1452580_a_at Mrpl21 3.1 173 12
理想情况下,grepping是不区分大小写的模式。
我怎样才能做到这一点 您的示例实际上不需要使用正则表达式
定义一个函数,该函数返回给定字符串是否包含列表中的任何元素
list_to_grep = ['Mrpl21', 'lipn', 'XXX']
def _grep(x, list_to_grep):
"""takes a string (x) and checks whether any string from a given
list of strings (list_to_grep) exists in `x`"""
for text in list_to_grep:
if text.lower() in x.lower():
return True
return False
创建遮罩:
mask = df.ProbeGenes.apply(_grep, list_to_grep=list_to_grep)
使用此掩码筛选数据帧:
df[mask]
这将产生:
ProbeGenes sample1 sample2 sample3
0 1431492_at Lipn 20.3 130 1
2 1452580_a_at Mrpl21 3.1 173 12
注意,这对小数据集很有效,但我在大数据帧(~10GB)中将函数应用于文本列时经历了不合理的长时间,在这种情况下,将函数应用于列表所需的时间要少得多,我不知道为什么
出于我无法理解的原因,类似这样的东西可以让我更快地过滤
>>> from functools import partial
>>> mylist = df.ProbeGenes.tolist()
>>> _greppy = partial(_grep, list_to_grep=list_to_grep)
>>> mymask = list(map(_greppy, mylist))
>>> df[mymask]