2

My problem is quite difficult to explain and I'm unsure if it's even possible to do what I'm asking, but I will try my best to explain.

Basically, I have a CSV file with data, and I want to extract specific cells and set them as a value in an object. Each row in the CSV contains information about an individual item. Currently, I have it hard coded using the pandas library and by doing df.iloc[0][1], etc. However, I want to be able to loop through the whole CSV and extract individual cells and add them to multiple objects, so I don't have to hard code every row manually.

Hopefully, the code will help show what I mean:

df = pd.read_csv('Options.csv')

My Class:

    class Option:
    def __init__(self, type, name, S, K):

        self.type = type
        self.name = name
        self.S = S
        self.K = K 

Current Extraction from CSV:

o1 = Option(df.iloc[0, 1], df.iloc[0][2], df.iloc[0][3], df.iloc[0][4])
o2 = Option(df.iloc[1, 1], df.iloc[1][2], df.iloc[1][3], df.iloc[1][4])

etc.

I still want to be able to select individual values of each option, for example, print(o1.name), o6.type, etc.

0

2 Answers 2

1

you need to iterate over every row from 0 to the maximum of rows in the document. For each iteration you create a new instance of the Option class.

Here is some example code:

df = pd.read_csv('Option.csv')

row_amount = 5 # put the amount of rows that the csv file contains here or get it with pandas 

options = []

for row in range(0, row_amount):
    option = Option(df.iloc[row, 1], df.iloc[row, 2], df.iloc[row, 3], df.iloc[row, 4])
    options.append(option)
Sign up to request clarification or add additional context in comments.

4 Comments

Would it sill be possible to select individual options using this code. For example: print(o1.type)
yes of course, you can choose any element of the options list by using the following syntax: options[x]. Which means that you can use the following line to print the type of the first row: print(options[1].type)
Okay, Thanks, that makes sense. Final question, how do I iterate through the list of options, to allow me to perform methods from my class. I have tried a for loop but keep getting errors.
Just figuired it out!
1

This will give you a list of of your Option objects:

options = df.apply(lambda x: Option(x[1], x[2], x[3], x[4]), axis=1)

options_list = options.values.tolist()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.