Reputation: 325
I have parsed data in dataframes by using Pandas. I need to insert the data into class that I created.
My class:
class Message:
time = None
id = None
type = None
source = None
destination = None
def __init__(self, time, id, type, source, destination):
self.time = time
self.id = id
self.type = type
self.source = source
self.destination = destination
I'm going through the dataframes and trying to insert the output into the attributes of the class as following:
newMessage=Message()
for index, row in df.iterrows():
newMessage.__init__(row['time'], row['id'], row['type'], row['source'], row['destination'])
print(row['time'], row['ID'], row['TYPE'], row['Source'], row['Destination'])
The exception it throws:
TypeError: __init__() missing 7 required positional arguments
I don't know how to call the class and the arguments, please help.
Upvotes: 0
Views: 522
Reputation: 1486
You can explore the powerful use of dataclasses or NamedTuple:
from dataclasses import dataclass
@dataclass
class Message:
time: str #adjust the datatype to suit your usecase
id: int
type_: str
source: str
destination: str
for index, value in df.iterrows():
newTelegram = Message(*value)# unpack the values
Upvotes: 1
Reputation: 23825
How about the below ? Use dataclass and get a clean solution
import pandas as pd
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
points = []
df = pd.DataFrame([{'x':12,'y':6},{'x':45,'y':33}])
for index, row in df.iterrows():
points.append(Point(**row))
print(points)
output
[Point(x=12, y=6), Point(x=45, y=33)]
Upvotes: 0
Reputation: 464
You could try something like that:
class Message:
time = None
id_ = None
type_ = None
source = None
destination = None
def __init__(self, time, id_, type_, source, destination):
self.time = time
self.id_ = id_
self.type_ = type_
self.source = source
self.destination = destination
for index, row in df.iterrows():
newTelegram = Message(row['time'], row['id'], row['type'], row['source'], row['destination'])
print(newTelegram.time)
print(getattr(newTelegram, "time"))
Note that both id & type are keywords in Python.
Upvotes: 1