3

Using pandas version 0.19.0, I have a dataframe with compiled regular expressions inside. I want to loop over the dataframe and see if any of the regular expressions match a value. I can do it with two for loops, but I can't figure out how to do it so that it'll return a same sized dataframe.

import pandas as pd
import re

inp = [{'c1':re.compile('a'), 'c2':re.compile('b')}, {'c1':re.compile('c'),'c2':re.compile('d')}, {'c1':re.compile('e'),'c2':re.compile('f')}]
df = pd.DataFrame(inp)
for i,v in df.items():
  for a in v:
    if (a.match('a')):
      print("matched")
    else:
      print("failed")

This fails:

[a.match('a') for a in [v for i,v in df.items()]]

AttributeError: 'Series' object has no attribute 'match'

What I want:

[a.match('a') for a in [v for i,v in df.items()]]
              c1                                         c2
0   <_sre.SRE_Match object; span=(0, 1), match='a'>     None
1   None                                                None
2   None                                                None

1 Answer 1

2

It looks like you need to use the applymap method. See the docs here for more info.

df.applymap(lambda x: x.match('a'))

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.