简体   繁体   中英

Assign individual tuple items to multiple dataframe columns using df.apply() method?

I have a dataframe with two columns A and B and a user-defined function that performns two calculations based on the values in A and returns a tuple with two items, output1 and output2 .

df = pd.DataFrame({'A':[1,2,3,4,5],'B':[5,4,3,2,1]})

def myfunc(row):

    selected_row = row['A']

    output1 = selected_row + 10
    output2 = selected_row + 20

    return (output1, output2)

What I'd like to do is assign the values of output1 and output2 to two separate dataframe columns, C and D . I'm so far able to assign the entire returned tuple (with both items) to a signle column as such:

df['C'] = df.apply(myfunc,axis=1)

I'd like to be able to do this for two different columns, with output1 going to column C and output2 going to column D ; I'm visualizing something like this:

df['C'], df['D'] = df.apply(myfunc,axis=1)

Any help or suggestions are much appreciated.

Does myfunc do anything that actually requires both columns? In your example it doesn't, so you actually don't need to use apply (and probably don't want to, because it's slow).

You could use df.assign instead:

df.assign(C=lambda x: xA + 10, D=lambda x: xB + 20)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM