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.


  • $\begingroup$ What does your data look like? Print your dataframe and column headers. Probably a column mismatch. $\endgroup$ – EchoCache Jan 7 at 10:00
  • $\begingroup$ Hi, I have also tried with different column also , i get a similar error KeyError: (1, 'occurred at index 0') $\endgroup$ – cvg Jan 7 at 10:03
  • $\begingroup$ 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) $\endgroup$ – EchoCache Jan 7 at 10:38
  • 1
    $\begingroup$ I think this is poor way of applying function in pandas, maybe explain a bit what you want to do? $\endgroup$ – Yohanes Alfredo Jan 7 at 14:35
  • $\begingroup$ 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. $\endgroup$ – vivek Jan 7 at 14:48