The following Python code works fine
import pandas as pd
df = pd.DataFrame(data = {'a': [1, 2, 3], 'b': [4, 5, 6]})
def myfun(a, b):
return [a + b, a - b]
df[['x', 'y']] = df.apply(
lambda row: myfun(row.a, row.b), axis=1)
The resulting pandas dataframe looks like:
print(df)
a b x y
0 1 4 5 -3
1 2 5 7 -3
2 3 6 9 -3
However, if I try to add two more columns,
df[['xx','yy']] = df.apply(lambda row: myfun(row.a, row.b), axis=1)
I get the error message,
KeyError: "['xx' 'yy'] not in index"
How come? And what is the correct way to do this?
Many thanks!
//A
Need convert return output to Series
:
def myfun(a, b):
return pd.Series([a + b, a - b])
df[['x', 'y']] = df.apply(
lambda row: myfun(row.a, row.b), axis=1)
print (df)
a b x y
0 1 4 5 -3
1 2 5 7 -3
2 3 6 9 -3
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments