Importing agents and their attributes from CSV in mesa

307 Views Asked by At

My data is in .csv format and each row of data represents each agent while each column represents a certain attribute.

My question is how to assign agents and their attributes from a csv file in Mesa?

Could anyone help me with how to import them in Mesa please?

Thanks.

1

There are 1 best solutions below

0
On

To import a .csv and turn them into attributes you want to know how you are reading in the file and then pass that into the agent class as you are creating it.

For example:

you have 'people.csv':

         agent, height, weight
         bill, 72 in, 190lbs
         anne, 70 in, 170lbs

you read in as a list of lists:

import csv
people = []

with open('people.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
         if line_count == 0:
            pass #skips the column headers
            line_count += 1
         else: 
            people.append(row)
            # This will look like [[ 'bill', '72 in', '190lbs'], ['anne', '70 in',\ 
            #'170lbs']]

you pass in a row into your agent instantiation, this would typically occur in the creation of your agent schedule in the model module:

  for i in range(number_of_agents):
        a = myAgent(i, self, row[i])
        self.schedule.add(a)

you assign the row variables to agent attributes:

  class myAgent(Agent): 
       def __init__(self, unique_id, model, row): 
            super().__init__(unique_id, model)
            self.name = row[0] # e.g bill
            self.height = row[1] # e.g. 72 in
            self.weight = row[2] # e.g. 190 lbs