Python Forum
list comprehension with regular expression - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: list comprehension with regular expression (/thread-3419.html)



list comprehension with regular expression - aibrain - May-22-2017

Wanted to do something like this:
# get rid of negative values for age
raw={'name': ['a', 'b', 'c', 'd', 'e'], 'age': [20,21,-1,22,-1]}
data=pd.DataFrame(raw)
cdata=pd.DataFrame()
cdata=data[data['age'] > 0]
print(cdata)
output:
   age name
0   20    a
1   21    b
3   22    d

but with str (couldn't so ended up with this):
# get rid of names with digits
raw={'name': ['a', '3', 'c', 'd', 'e'], 'age': [20,21,20,22,21]}
data=pd.DataFrame(raw)
cdata=pd.DataFrame()
j=[]
for i in data.index:
    j.append(not bool(re.search(r'\d',str(data.ix[i]['name']))))
cdata=data[j]
print(cdata)
any ideas how to do this without a loop OR another faster way?


RE: list comprehension with regular expression - zivoni - May-22-2017

data[~data.name.str.contains(r"\d")]
you dont need to create empty dataframes.