简体   繁体   中英

Passing multiple columns of a dataframe to fetch values and assign it to new columns

I'm posting using mobile, so apologize for not providing the code. My organization doesn't let me access this site.

I have been unable to achieve the following.

SomeFunction(col1, col2): 
            #Do somethinng
            Return list

df[col3],  df[col4]  = df[[col1, col2]].applymap(SomeFunction)

Note: I've been able to archive this using for loop but it's taking lots of time. There are many more columns so I must specify the column names in data dataframe.

I think you need apply with axis=1 for processes by rows, but there are also loops under the hood, so big improvement of performance is problematic:

def SomeFunction(col1, col2): 
    L = [1,2]
    return pd.Series(L)

df[['col3', 'col4']]  = df.apply(lambda x: SomeFunction(x['col1'], x['col2']), axis=1)

For improvement performance is best rewrite your function by pandas vectorized functions if possible.

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