0

I have a function as below. I want to apply it over a row of a dataframe and return 2 values and then copy those 2 values in 2 columns. My both approaches fail (last 2 lines)

data1 = [['Alex',10,5,0],['Bob',12,4,1],['Clarke',13,6,0],['brke',15,1,0]]
df5 = pd.DataFrame(data1,columns=['Name','Age','weight','class'],dtype=float)
#print (df)
def calculate_distance2(row):
    return pd.Series([row['Age']+row['weight'],row['Age']-row['weight']])

df5.apply(calculate_distance2, axis=1)

df5[['distance0'],['d6']]= df5.apply(calculate_distance2, axis=1)
df5['distance0'],df5['d6']= df5.apply(calculate_distance2, axis=1)

df5

1 Answer 1

1

IIUC

def calculate_distance2(row):
    return [row['Age']+row['weight'],row['Age']-row['weight']]
df5['distance0'],df5['d6']=calculate_distance2(df5)
df5
     Name   Age  weight  class  distance0    d6
0    Alex  10.0     5.0    0.0       15.0   5.0
1     Bob  12.0     4.0    1.0       16.0   8.0
2  Clarke  13.0     6.0    0.0       19.0   7.0
3    brke  15.0     1.0    0.0       16.0  14.0
Sign up to request clarification or add additional context in comments.

2 Comments

without apply how does python understand that it needs to apply the function over each row?
@user2543622 pandas is vectorized , when you do basic calculation , it will base on the index which means you even can do , df['distance0']=df['Age']+df['weight']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.