从python中的字母数字列中删除整数值

时间:2014-07-14 11:41:12

标签: python regex

我是python的新手,在一项琐碎的任务中苦苦挣扎。我有一个称为region的字母数字列。它有以/ /例如/ health / blood pressure等开头的条目和整数值。所以通常很少有观察结果如下:

/health/blood pressure
/health/diabetes
7867
/fitness
9087
/health/type1 diabetes

现在我想删除所有带整数值的行/个案。因此,在将数据集导入python shell之后,它将区域显示为对象。我打算用一种正则表达式来解决这个问题。所以我做了以下事情:

pattern='/'
data.region=Series(data.region)
matches=data.region.str.match(pattern)
matches

这里给出一个布尔对象,解释每个模式是否在数据集中。所以我得到这样的东西:

0  true
1 false
2 true
3 true
.........
so on.

现在我更进一步说明如何删除带有false标记的匹配boolean对象的行。如果声明不起作用。如果有人可以提供某种帮助,那就太棒了!!

谢谢!

1 个答案:

答案 0 :(得分:1)

好像你正在使用pandas框架。所以我不确定这是否有效:

您可以尝试:

matches = [i for i in data.region if i.str.match(pattern)]

在python中,这称为列表推导,它遍历data.region中的每个条目并检查您的模式并在模式匹配时将其放入列表中(并且'if'之后的表达式因此为真)。 p>

请参阅:https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

如果要映射每个区域的那些,您可以尝试创建一个字典,使用以下字典理解将区域映射到列表:

matches = {region: [i for i in data.region if i.str.match(pattern)] for region in data}

请参阅:https://docs.python.org/2/tutorial/datastructures.html#dictionaries

然而,你肯定会离开熊猫框架的领域。这可能最终失败的区域不是整数/字符串而是列表本身(因为是援助我不知道熊猫足以判断)。

在这种情况下,您可以尝试:

matches = {}
for region in list_of_regions:
    matches[region] = [i for i in data.region if i.str.match(pattern)]

与给定的区域列表基本相同,并且在for循环中明确表达了dict理解。