0

How do you store multiple returns of a function in one DataFrame. Here is an example in MRE.

import pandas as pd
import numpy as np

def example(height):
  weight = height * 2
  wingspan = height * 0.8

  return weight, wingspan

df = pd.DataFrame(np.array([80, 60, 70]),
               columns=['height'])

Now if were doing this with a function that only returned one output I would do it like this.

def example_row(row):
  return example(row.height)

df['weight'] = df.apply(example_row, axis=1)

But I'm not sure how to add two columns one for weight and one for wingspan. Thanks in advance.

  • 1
    This might help? https://stackoverflow.com/questions/23690284/pandas-apply-function-that-returns-multiple-values-to-rows-in-pandas-dataframe – Anna Semjén Oct 06 '20 at 22:13

1 Answers1

0

Since you can get the index by name, write the index by .loc.

import pandas as pd
import numpy as np

df = pd.DataFrame(np.array([80, 60, 70]), columns=['height'])

def example_row(x):
    df.loc[x.name, 'weight'] = x[0] * 2
    df.loc[x.name, 'wingspan'] = x[0] * 0.8

df.apply(example_row, axis=1)

height  weight  wingspan
0   80  160.0   64.0
1   60  120.0   48.0
2   70  140.0   56.0
r-beginners
  • 31,170
  • 3
  • 14
  • 32