How to apply a function over rows within a single column of a pandas data frame?

Viewed 118

I am using an address parsing library which accepts strings in the following way

import pyap
test_address = """
   4998 Stairstep Lane Toronto ON   
    """
addresses = pyap.parse(test_address, country='CA')
for address in addresses:
        # shows found address
        print(address)
        # shows address parts
        print(address.as_dict())

I would like to use this function on every row of a single pandas data-frame column.The dataframe contains two columns (id,address) This is what I have so far

addresses.apply(lambda x: pyap.parse(x['address'], country='CA'),axis=1)

Though this runs, it results in a series instead of a 'pyap.address.Address'

1 Answers

You have to do what you do, but in reverse: Let's say your dataframe is this:

d = [{'id': '1', 'address': '4998 Stairstep Lane Toronto ON'}, {'id': '2', 'address': '1234 Stairwell Road Toronto ON'}] 
df = pd.DataFrame(d) 
df

    id  address
0   1   4998 Stairstep Lane Toronto ON
1   2   1234 Stairwell Road Toronto ON

Extract these addresses to a list

address_list = df['address'].tolist()

and then process each with pyapp:

for al in address_list:
   addresses = pyap.parse(al, country='CA')
   for address in addresses:
        print(address)
        print(address.as_dict())

Let me know if it works.

Related