1

I have defined the following function that generates as output a tuple, and I need to assign the result to two different columns of a dataframe.

The functions just tooks a x and y coordinate and converts it to a different coordinate:

plot_shot(x,y)

I have developed the following code that it works, but I am looking for a smarter solution that allows me to assign the tuple in the apply lambda line:

df_shots['temporary'] = df_shots.apply (lambda a: plot_shot(a['x'],a['y'],0,15,-3,'left','bottom'), axis=1)
df_shots['x_converted'] = df_shots['temporary'].apply (lambda x: x[0])
df_shots['y_converted'] = df_shots['temporary'].apply (lambda x: x[1])
df_shots.drop('temporary', axis=1, inplace = True)

I am assuming that this can be donde in one line instead of this.

Thanks in advance.

agm
  • 317
  • 3
  • 15
  • Would this solution do the trick? [unpacking function return into pandas dataframe columns](https://stackoverflow.com/questions/43008866/unpacking-function-return-into-pandas-dataframe-columns) – B Man Feb 26 '20 at 19:55

2 Answers2

0

I've not tested the code, but maybe some of the following works.

This probably wont work:

df_shots['x_converted'], df_shots['y_converted'] = df_shots.apply (lambda a: plot_shot(a['x'],a['y'], ...), axis=1)

This probably does:

df_shots['x_converted'] = df_shots.apply (lambda a: plot_shot(a['x'],a['y'], ...)[0], axis=1)
df_shots['y_converted'] = df_shots.apply (lambda a: plot_shot(a['x'],a['y'], ...)[1], axis=1)

Sorry no pandas installation to test..

Lukr
  • 659
  • 3
  • 14
0

You can assign the two columns directly by pd.DataFrame:

df = pd.DataFrame({"new":[(1,2),(3,4),(5,6)]})

df[['new1','new2']] = pd.DataFrame(df["new"].values.tolist())

print (df)

      new  new1  new2
0  (1, 2)     1     2
1  (3, 4)     3     4
2  (5, 6)     5     6
Henry Yik
  • 22,275
  • 4
  • 18
  • 40