samhar
samhar

Reputation: 13

Name a function after a string

I am trying to read different tabs from an excel file. For each tab I a want to perform a linear regression that returns a function (1st order polynom) I want to store the function under the name of tab or the data frame

import pandas as pd
import numpy as np


dfs = pd.read_excel(r'Prod.xlsx', sheet_name=None)
for df in dfs:
     func = np.poly1d(np.polyfit(dfs[df].P, dfs[df].Q, 1))
     def df(x):
         return func(x)

I would like to have a function with an individual name for regression each of the sheets. I tried also

for df in dfs:
     df = np.poly1d(np.polyfit(dfs[df].P, dfs[df].Q, 1))
     

but the problem is that df is being overwritten!

Upvotes: 0

Views: 79

Answers (1)

2e0byo
2e0byo

Reputation: 5954

I want to store the function under the name of tab or the data frame

I think you just want a dictionary of functions:

polynomial_functions = {}
tabs = pd.read_excel(r'Prod.xlsx', sheet_name=None)
for tab in tabs:
     func = np.poly1d(np.polyfit(dfs[df].P, dfs[df].Q, 1))
     polynomial_functions[tab] = func

Then you can call later with

polynomial_functions["tab_name"]()

Note that I've renamed your df to tab to make it clearer what a dataframe represents.

Upvotes: 3

Related Questions