[英]Removing integer values from a alphanumeric column in python
我是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.
現在,我被進一步困住了如何刪除帶有錯誤標記的匹配布爾對象的行。 如果語句不起作用。 如果有人可以提供某種幫助,那就太好了!!
謝謝!!
似乎您正在使用pandas框架。 所以我不完全確定這是否有效:
你可以試試:
matches = [i for i in data.region if i.str.match(pattern)]
在python中,這稱為列表理解,它遍歷data.region中的每個條目,並檢查您的模式,如果模式匹配則將其放在列表中(因此'if'之后的表達式為true)。
請參閱: https : //docs.python.org/2/tutorial/datastructures.html#list-comprehensions
如果要為每個區域映射這些區域,則可以嘗試創建一個字典,使用以下dict-comprehension將區域映射到列表:
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理解,這基本上是相同的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.