Python Forum
class constructor with dataframe - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: class constructor with dataframe (/thread-19049.html)



class constructor with dataframe - UGuntupalli - Jun-11-2019

All,
I have a very simple example of a class definition. Can someone kindly provide an example of how I can instantiate multiple objects at once by passing the constructor a data frame ?

class Person: 
  
    # init method or constructor  
    def __init__(self, name, dataframe = None): 
        if not dataframe:
            self.name = name 
        else: 
            print('dataframe received')
            
  
    # Sample Method  
    def say_hi(self): 
        print('Hello, my name is', self.name) 
  
p = Person('Uday') 
p.say_hi()

# My data frame 
students_list = ['uday','mark','sam','tom']
students_df = pd.DataFrame()
students_df['names'] = students_list
So I would like to efficiently create 4 class objects for each name in the dataframe


RE: class constructor with dataframe - SheeppOSU - Jun-11-2019

So you mean something like this, but with a dataframe
class student:
    def __init__(self, name):
        self.name = name

    def introduction(self):
        print('Hi, I\'m %s' %self.name)

nameList = ['Mark', 'Mary', 'Luke', 'Sally', 'Lerry']
studentList = []
for student in nameList:
    studentList.append(student(student))

for student in studentList:
    student.introduction()



RE: class constructor with dataframe - UGuntupalli - Jun-11-2019

@SheeppOSU,
Yes