Aman Agarwal
Aman Agarwal

Reputation: 31

How to write to separate columns based on function output

I have an internal function which returns two different values, and I want to be able to write that to separate columns of the same dataframe

df = pd.DataFrame([{'a': 15, 'b': 15, 'c': 5}, {'a': 20, 'b': 10, 'c': 7}, {'a': 25, 'b': 30, 'c': 9}])
def test(a):
    return a*2, a*3    

I used the below to write to one column at a time, but even after playing around cannot figure how I can write to two columns without having to create two separate functions and calling the apply function twice. My original implementation has a API call which is kind of slow, so calling the function and API twice for separate columns slows it down tremendously.

df['Two Times'] = df.apply(lambda row: test(row['a']), axis=1)

I tried the below too, but get a ValueError: Must have equal len keys and value when setting with an iterable

df[['Two Times', 'Three Times']] = df.apply(lambda row: test(row['a'], axis=1)

I would want to have a column 'Two Times' that has 2*a for each row in df, and similarly for a column 'Three Times' would want 3*a for each row.

Upvotes: 0

Views: 47

Answers (1)

geekzeus
geekzeus

Reputation: 895

Adding pd.Series should do the work.

df[['Two Times', 'Three Times']] = df.apply(lambda row: pd.Series(test(row['a'])), axis=1)

OR

#create function like this 
def test(a):
    return pd.Series((a*2,a*3))

Both should work

Upvotes: 1

Related Questions