-1

After creating a DataFrame and a class, I wanna to use the indexes as instance of the created class. It sounds weird but let me explain it :D

I have for instance this Dataframe df:

  Name 'Jane' 'Max'

  Age   25     20 

the Name and the Age are the indexes, which are in string type. I want to convert it into an object so that I can use it as an instance of the class „I_am_a_class“ as the following:

  df.index[0]
  output: 'Name'

  df.index[0] = I_am_a_class(attributes) 
  df.index[1] = I_am_a_class(attributes)

This does not work because the df.index[0] is in string format. I'm wondering whether there is a way to convert the df.index into an adequate format so that it becomes possible to realize that ?

Adarsh Wase
  • 1,727
  • 3
  • 12
  • 26
jess
  • 81
  • 1
  • 7

1 Answers1

1

EDIT: Thanks for explaining what your goal is. You could do the following if you only have a few entries in your dataframe:

import pandas as pd

class legend():
    def __init__(self,unit,meaning):
        self.unit= unit
        self.meaning= meaning
    
    
df = pd.DataFrame(
    data = {
        'unit':['m/s','Pa'],
        'meaning':['distance moved divided by the time','force divided by the area'], 
    },
    index=['velocity','pressure'],
)

velocity = legend(df.loc['velocity','unit'], df.loc['velocity','meaning'])
pressure = legend(df.loc['pressure','unit'], df.loc['pressure','meaning'])


print(velocity.unit)
print(velocity.meaning)

If you have too many, or a variable number of rows in the dataframe so you can't make the variables by-hand like above AND if you really really don't want to use a dictionary for some reason, then you can do the following, but it's frowned upon:

import pandas as pd

class Legend():
    def __init__(self,unit,meaning):
        self.unit= unit
        self.meaning= meaning
    
    
df = pd.DataFrame(
    data = {
        'unit':['m/s','Pa'],
        'meaning':['distance moved divided by the time','force divided by the area'], 
    },
    index=['velocity','pressure'],
)

#If you REALLY don't want to use a dictionary you can use exec to create arbitrary variable names
#This is bad practice in python. You can read more about it at the link below
#https://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-via-a-while-loop
for i,r in df.iterrows():
    exec('{} = Legend("{}","{}")'.format(i,r['unit'],r['meaning']))


print(velocity.unit)
print(velocity.meaning)
mitoRibo
  • 4,468
  • 1
  • 13
  • 22