Python Forum
class constructor with dataframe
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
class constructor with dataframe
#1
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
Reply
#2
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()
Reply
#3
@SheeppOSU,
Yes
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why doesn't calling a parent constructor work with arbitrary keyword arguments? PurposefulCoder 4 930 Jun-24-2023, 02:14 PM
Last Post: deanhystad
  Cannot convert the series to <class 'int'> when trying to create new dataframe column Mark17 3 8,498 Jan-20-2022, 05:15 PM
Last Post: deanhystad
  Not including a constructor __init__ in the class definition... bytecrunch 3 11,807 Sep-02-2021, 04:40 AM
Last Post: deanhystad
  How to apply a class method to an entire dataframe column tirtha9 1 5,127 Jan-03-2021, 04:44 AM
Last Post: klllmmm
  syntaxerror when entering a constructor MaartenRo 2 1,979 Aug-03-2020, 02:09 PM
Last Post: MaartenRo
  error in constructor overriding in python3 srm 1 1,791 Jul-18-2019, 12:21 PM
Last Post: ichabod801
  This constructor takes no arguments Friend 2 5,315 Jun-26-2019, 02:54 PM
Last Post: Friend
  Overload of constructor psosmol 2 2,798 Apr-17-2019, 05:10 AM
Last Post: psosmol
  Constructor Rajesh1978 2 3,194 May-22-2018, 05:18 PM
Last Post: micseydel
  I'm trying to make a constructor without hardcoding all of the values RedSkeleton007 7 4,462 Apr-05-2018, 11:12 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020