1

I have a function which returns a tuple with two elements in python. I'm going to use this function to create two new columns in my dataframe in pandas. This is the code I have now

df['A','B'] = df.apply(lambda x: my_fun (X['A'], x['B'], other_arguments)[0:2], axis=1)

my_fun returns tuples with 5 elements and I'm taking the first two elements to create the new columns. However it creates only one column and set the value of that column to the tuple that my_fun returns. How can I create two columns instead of one?

HHH
  • 6,085
  • 20
  • 92
  • 164
  • this should help https://stackoverflow.com/q/34074663/9754169 – Yuca Feb 12 '19 at 15:46
  • It will obviously create one column with values of column A and B in tuple. What is your sample Dataframe and expected output – Vaishali Feb 12 '19 at 15:58

2 Answers2

1

Try

df['A'], df['B'] = df.apply(lambda x: my_fun(x['A'], x['B'], other_arguments)[:2], axis=1)

if my_fun returns a tuple with 5 elements and you only want to keep the first 2, then use a slice with the function call [:2]

PyRsquared
  • 6,970
  • 11
  • 50
  • 86
1
df[['A','B']] = df.apply(lambda x: my_fun (X['A'], x['B'], other_arguments)[0:2], axis=1).apply(pd.Series)
iamklaus
  • 3,720
  • 2
  • 12
  • 21