0

Have some way to apply a function in a pandas.Series using different values of another pandas.Series? I know that have the pandas.Series.apply(), but I need something like that:

array1 = pandas.Series([1, 2, 3, 4])
array2 = pandas.Series([5, 5, 6, 0])

def func(x, y):
    return x+y

print(array1.apply(func, args = array2))


Out:
    0 6
    1 7
    2 9
    3 4

In other words, I need apply a function in a pandas.DataFrame column by I need use another column of same pandas.DataFrame. Using the same function func:

df = pandas.DataFrame({'a': [1, 2, 3, 4], 'b': [5, 5, 6, 0]})
df['c'] = df['a'].apply(func, args = df['b'])

print(df)


Out:
       a   b   c
    0  1   5   6
    1  2   5   7
    2  3   6   9
    3  4   0   4

Thank you!

I need use the apply because I use multiprocessing like pandarallel, so I just change apply() for parallel_apply(), someone know a way to do it? Use multiprocessing with operations that use two columns?

2 Answers 2

1

If you want to add columns from two dataframes then instead of

print(array1.apply(func, args = array2)) 

you can use

print(func(array1, array2))                                                                                                                                                               
0    6
1    7
2    9
3    4

If you want to add two columns of the same dataframe, you can do that simply in the following way:

df['c'] = func(df['a'], df['b']) 

print(df) 
     ...:                                                                                                                                                                                           
   a  b  c
0  1  5  6
1  2  5  7
2  3  6  9
3  4  0  4
Sign up to request clarification or add additional context in comments.

1 Comment

I need use the apply because I use multiprocessing like pandarallel, so I just change apply() for parallel_apply(), have some way to do it with that you said? I just use multiprocesing using two columns of a pandas.DataFrame()
0

For the specific case you can just use:

df['c'] = df['a'] + df['c']

and for the principal function you use Numpy like in this example

df['c'] = numpy.exp(df['a']) + df['b']

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.