Burbs
Burbs

Reputation: 72

Can I generate variables from a pd.DataFrame?

I'm currently reworking an old model. This model uses a lot of different parameters and constants. The initial values of these parameters and constants, and their name are stored in a csv. I imported this as a pandas df.

What I want is a code that goes line by line through the pandas df and creates parameters based on the name and value in the df (such that each parameter that is in the df is callable by its name).

How can I best approach this problem?

Thanks in advance!

 import os
 import glob
 import pandas as pd
 import numpy as np

 # Working directory
 md = os.path.dirname(os.path.realpath(__file__))
 path_in = os.path.join(md, 'Input')
 path_out = os.path.join(md, 'Output')

 # Input files
 csv_files = sorted(glob.glob(os.path.join(md, 'Input', '*.csv')))
 excel_files = sorted(glob.glob(os.path.join(md, 'Input', '*.xlsx')))

 # read .DAT
 df_DAT = pd.read_csv(csv_files[1], skiprows=2, usecols=[1,3,4,5,6,7,8]) # B,D,E:I
 df_DAT['value'] = df_DAT['value'].astype(int)

 # Code
 # Create all constants and or variables
 def constant():
      for i in range(len(df_DAT)):
           print(df_DAT.iloc[i,0], ' value: ', df_DAT.iloc[i,2], df_DAT.iloc[i,1])

Upvotes: 1

Views: 54

Answers (1)

remeus
remeus

Reputation: 2449

You are probably looking for exec():

exec(f"{df_DAT.iloc[i, 0]} = {df_DAT.iloc[i, 1]}")

It creates a new variable with the first value of the ith row as its name and the second value of the ith row as its value.

Note that the names must be valid Python variable names or you will raise a SyntaxError.

Upvotes: 1

Related Questions