Michael Discenza
Michael Discenza

Reputation: 3330

Applying a python function that returns a list and writing to columns of dataframe

Is there a way that I can apply a function to a pandas dataframe that returns a list for each row that it is applied to, and then take that list and put each item into new columns of that existing dataframe?

For example the function I have returns for a given row the list below of length 9

    [u'Republic Of Congo Permanent Mission to the United Nations',
    u'Embassy / Consulate',
    u'10021',
    u'Permanent Mission of Germany to the United Nations',
    u'Embassy / Consulate',
    u'10021',
    u'Permanent Mission of Kenya to the United Nations',
    u'Embassy / Consulate',
     u'10021']

And I want to then store those values in a columns labeled:

     colnames= ['prop1_name', 'prop1_type', 'prop1_zip',
        'prop2_name', 'prop2_type', 'prop2_zip',
        'prop3_name', 'prop3_type', 'prop3_zip'] 

Right now the return of the apply function is a list of lists each of the inner lists is a 9 item list like that shown above. I am fine putting the response into a new dataframe such as the below, but I haven't figured out how to get the apply function to write to each new row for each return or get the list of lists in to the right form.

   df_new = pd.DataFrame(index=range(0,sample_size), columns=colnames)

Upvotes: 0

Views: 1912

Answers (1)

user1827356
user1827356

Reputation: 7022

This should work

df_new.apply(lambda r: pd.Series(function_taking_row(r), index=colnames), axis=1)

Upvotes: 1

Related Questions