0

I read a txt file into a dataframe and now trying to iterate over the rows of the pandas dataframe and create a student object for each of the data entries. and eventually, store the student objects in a list "students".

I am a little confused about how to iterate the rows and add students objects to the students list. Can anyone help me creating this list? thank you

students = []
import pandas as pd

data = pd.read_csv('students.txt')
df = pd.DataFrame(data)
print(df)

file output

 firstname   lastname     status  gpa
0      Mike     Barnes   freshman  4.0
1       Jim  Nickerson  sophomore  3.0
2      Jack    Indabox     junior  2.5
3      Jane        Doe   freshman  1.1
4      Jane     Miller     senior  3.6
5      Mary      Scott     senior  2.7
6      John        Doe     senior  1.0
7     Elvis    Presley  sophomore  1.5
8    Batman      Wayne   freshman  0.5
9      Jack        Pot     junior  2.0
intedgar
  • 631
  • 1
  • 11
riven
  • 27
  • 4

1 Answers1

1

You can use the .iterrows() function of the dataframe in a loop and access each column in the specific row by .<name> to create your instance of a student class:

for index, row in df.iterrows():
    
    row.firstname
    row.lastname
    row.status
    row.gpa
Arne Decker
  • 808
  • 1
  • 3
  • 9
  • Iteration in Pandas is an anti-pattern. https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas – Tyler Liu Oct 31 '21 at 21:10
  • @tyler how would you vectorise object creation based on row data? – Riley Oct 31 '21 at 21:21
  • If OP is simply converting rows of a text file to a list of objects, then Pandas is overkill. I would just read the file using `readlines()`. – Tyler Liu Oct 31 '21 at 21:28
  • thank you all! I used the first solution with student.append to save as a list. – riven Nov 03 '21 at 18:07