Wesspe
Wesspe

Reputation: 35

Pass tuple into function

So basicaly what i want is use this function:

def __init__(self, myTuple: tuple):

    for i in myTuple:
        print(i[1])
        self.dzien_tyg = i[1]
        self.godz_rozp = i[2]
        self.ilosc_godz = i[3]
        self.czestatliwosc = i[4]
        self.id_prowadzacego = i[5]
        self.id_sali = i[6]
        self.id_przedmiotu = i[7]
        self.rodzaj = i[8]
        self.nr_grupy = i[9]
        self.id_studia = i[10]
        self.nr_semetru = i[11]
        self.id_specjalnosci = i[12]

Using this code:

for row in df.iterrows():
    print(row)
    object = Grupa(*row)

What my pycharms says:

TypeError: __init__() takes 2 positional arguments but 3 were given

how is "row" looking:

(0, dzien        1
godz         1
ilosc        2
tyg          0
id_naucz    52
id_sala     79
id_prz      13
rodz         W
grupa        1
id_st       13
sem          1
id_spec      0
Name: 0, dtype: object)

And i cannot figure it out where does pycharms see those 3 arguments and how to fix it

Upvotes: 1

Views: 1245

Answers (1)

akuiper
akuiper

Reputation: 214927

Try to replace *row with row[1]:

for row in df.iterrows():
    print(row)
    object = Grupa(row[1])

When you iterrows(), each row as you can see from the print, is a two elements tuple, the first element is the row index, and the second element is a Series object that contains the actual data, when you use *row you pass both the index and series object to the constructor. But from __init__ definition, it seems you want only the row object.


And also if each row is going to be an object, then you don't need the for loop in __init__, with a minimum change to your original code:

def __init__(self, myTuple: tuple):

    i = myTuple
    print(i[1])
    self.dzien_tyg = i.iloc[0]     # be careful here when you index the Series object with
    self.godz_rozp = i.iloc[1]     # integers, use iloc to access elements and also note
    self.ilosc_godz = i.iloc[2]    # the indices are zero based
...

Alternatively, you can access more safely with the actual index:

def __init__(self, myTuple: tuple):

    i = myTuple
    print(i['dzien'])
    self.dzien_tyg = i['dzien']     
    self.godz_rozp = i['godz']     
    self.ilosc_godz = i['ilosc']    
...

Upvotes: 1

Related Questions