# passing a dataframe as a argument while applying a lambda function on a dataframe [closed]

I am applying a lambda function on a data frame and would like to add a new column to that dataframe, while applying the lambda function I am passing the data frame it self as a argument to the function. My code

def categorical_fare_mean(data,col,cat):
print('entered once')
data = data[data[col]==cat]['Fare']
fare_mean = data['Fare'].mean()
return fare_mean

dataset['weekday_encoded'] = dataset.apply(lambda x: categorical_fare_mean(dataset,x['weekday'],0) ,axis = 1)



This is giving me an error KeyError: (0, 'occurred at index 0') I am not sure where I am going wrong. Can some one help me with it.

Thanks

• What does your data look like? Print your dataframe and column headers. Probably a column mismatch. – EchoCache Jan 7 at 10:00
• Hi, I have also tried with different column also , i get a similar error KeyError: (1, 'occurred at index 0') – cvg Jan 7 at 10:03
• Pretty sure the problem is your column x["weekday"]. Try to use loc instead of data[data[col]==cat]['Fare']. Moreover you are trying to copy the dataset in the lambda function which is not necessary. So you should rewrite the function and use this to call it: dataset['weekday_encoded'] = dataset.apply(lambda x: categorical_fare_mean(x["weekday"],0) ,axis = 1) – EchoCache Jan 7 at 10:38
• I think this is poor way of applying function in pandas, maybe explain a bit what you want to do? – Yohanes Alfredo Jan 7 at 14:35
• I believe you are looking to take the mean of fare in the function, but I am not sure if you really need to go via lambda to apply this. Please explain the end outcome you are trying to achieve. – vivek Jan 7 at 14:48