How to add multiple columns to a dataframe using a function returning a serie

Question:

I have two dataframes :

import pandas as pd
df = pd.DataFrame({'Name':['Tom','Jhon','Dan'], 'start': [4,6,10], 'stop':[7,7,12]})
d = pd.DataFrame({'ID':['Tom','Tom','Tom','Tom','Jhon','Dan'],'game':[3,5,6,9,7,11] ,'hits': [10,12,9,8,8,6],'kills':[4,8,5,6,3,2]})

df:
enter image description here

d:
enter image description here

I want to add 2 columns to df based on conditional filtering d.
I was able to do it col by col :

def get_hits(row):
     return d[(d['ID']==row['Name']) & (d['game']>row['start']) & (d['game']<row['stop'])]['hits'].sum()
def get_kills(row):
    return d[(d['ID']==row['Name']) & (d['game']>row['start']) & (d['game']<row['stop'])]['kills'].sum()
df['ok_hits']=df.apply(lambda row: get_hits(row), axis=1)
df['ok_kills']=df.apply(lambda row: get_kills(row), axis=1)

enter image description here

Question: Is it possible to add two columns at the same time using the function below, returning a series?
In practice, I have to do it for a lot of columns.

def get_hits_kills(row):
    return d[(d['ID']==row['Name']) & (d['game']>row['start']) & (d['game']<row['stop'])][['hits','kills']].sum()
Asked By: Marvy

||

Answers:

df[['hits', 'kills']] = df.apply(get_hits_kills, axis=1) will do the job. For more information check apply documentation here.

Answered By: Zeno Dalla Valle
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.