I have a pandas dataframe that can be represented as follows:
myDF = pd.DataFrame({'value':[5,2,4,3,6,1,4,8]})
print(myDF)
value
0 5
1 2
2 4
3 3
4 6
5 1
6 4
7 8
I can add a new column containing the returned value from a function that acts on the contents of the 'value' column. For example, I can add a column called 'square', which contains the square of the value, by defining a function and then using lambda, as follows:
def myFunc(x):
mySquare = x*x
return mySquare
myDF['square'] = myDF['value'].map(lambda x: myFunc(x))
...to produce
value square
0 5 25
1 2 4
2 4 16
3 3 9
4 6 36
5 1 1
6 4 16
7 8 64
(N.B. The actual function I'm using is more complex than this but this simple squaring process is OK for illustration.)
My question is, can the myFunc() function return a tuple (or a dictionary or a list) that could be used to add multiple new columns in the dataframe? As a (very simple) example, to add new columns for squares, cubes, fourth powers, is it possible to do something akin to:
def myFunc(x):
mySquare = x*x
myCube = x*x*x
myFourth = x*x*x*x
return mySquare,myCube,myFourth
myDF['square'],myDF['cubed'],myDF['fourth'] = myDF['value'].map(lambda x: myFunc(x))
...to produce the following:
value square cubed fourth
0 5 25 125 625
1 2 4 8 16
2 4 16 64 256
3 3 9 27 81
4 6 36 216 1296
5 1 1 1 1
6 4 16 64 256
7 8 64 512 4096
Writing 3 separate functions would seem to be unnecessarily repetitive. None of the variations I've tried so far has worked (the above fails with: ValueError: too many values to unpack (expected 3)).
As mentioned above, the examples of squares, cubes and fourth powers are just for illustration purposes. I know that there are much more effective ways to calculate these values in a dataframe. However, I'm interested in the method to add several columns to a dataframe based on stepping through each cell of a column.