I have a list of values (could easily become a Series or DataFrame), on which I want to apply a function element-wise.
x = [1, 5, 14, 27]
The function itself returns a single row of a DataFrame (returning the original value x
and two result value columns), and I want to end up with a single DataFrame.
x Val1 Val2
0 1 4 23
1 5 56 27
2 14 10 9
3 27 8 33
The simple method is a for
loop over the list and row bind the results with df.append()
, but I'm sure there is a way to do this with the .apply()
family of functions. I just can't figure out exactly which to use. I'm pretty familiar with doing this type of thing in R, and am familiar with Python, just need to get my head around the pandas syntax.
EDIT: More concrete example for clarity
Example function:
def returnsquares(x):
return pd.DataFrame({"input": [x], "sq": x**2, "cube": x**3})
Input of the function is a scalar, output is a DataFrame with a single row (Not a series).
Code that works:
result = pd.DataFrame({}, columns=["input", "sq", "cube"])
for entry in x:
result = result.append(returnsquares(entry))
(The values of the output are obviously not the same as above, but are the same shape). Is there a better method for doing this?