How to iterate a function on my data frame and get values stored in the same data frame with the original values

601 Views Asked by At

The below is the function for finding probability(for being in a class) for one id(with multiple features and their one values) at a time. How would I iterate this function over an excel sheet having multiple rows and multiple features. I would like to add new columns next to existing columns showing the probability value which we will get by the below function. I have converted the data frame to dictionary, where column names are keys. SO, I have multiple values in each keys.

def predict_many(values, features):
    values = np.array(values).reshape(-1, 1)
    features = np.array(features)
    results = pd.DataFrame(data=values, index=features, columns=["X_value"])
    results["proba"] = results.apply(lambda row: predict_one(row.X_value, row.name), axis=1).values
    return results                                                               
1

There are 1 best solutions below

6
ilamaaa On

To apply a function similar to yours to each key value pair in a dictionary we would iterate over the dictionary passing the key value pairs, since the function returns a df we would then concat the dfs as they are returned

df2 = pd.DataFrame(columns = columns)
for key, value in d.items():
     temp_df = function_to_apply(key, value)
     df2 = pd.concat([df2, temp_df])

The dictionary you will be using may need to be transformed in order to get the desired results.