Python Forum
list comprehension with regular expression
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
list comprehension with regular expression
#1
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?
Reply
#2
data[~data.name.str.contains(r"\d")]
you dont need to create empty dataframes.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  List Comprehension Issue johnywhy 5 542 Jan-14-2024, 07:58 AM
Last Post: Pedroski55
  data validation with specific regular expression shaheen07 0 342 Jan-12-2024, 07:56 AM
Last Post: shaheen07
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 483 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  Using list comprehension with 'yield' in function tester_V 5 1,258 Apr-02-2023, 06:31 PM
Last Post: tester_V
  Regular Expression search to comment lines of code Gman2233 5 1,688 Sep-08-2022, 06:57 AM
Last Post: ndc85430
  list comprehension 3lnyn0 4 1,419 Jul-12-2022, 09:49 AM
Last Post: DeaD_EyE
  List Creation and Position of Continue Statement In Regular Expression Code new_coder_231013 3 1,673 Jun-15-2022, 12:00 PM
Last Post: new_coder_231013
  Need help with my code (regular expression) shailc 5 1,940 Apr-04-2022, 07:34 PM
Last Post: shailc
  Regular Expression for matching words xinyulon 1 2,179 Mar-09-2022, 10:34 PM
Last Post: snippsat
  List comprehension used differently coder_sw99 3 1,732 Oct-03-2021, 04:12 PM
Last Post: coder_sw99

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020