1

I have a class Asset that takes a name (should be entered with quotation marks). This will work fine: Apple = Asset ('AAPL') I want to turn all dataframe columns into Asset objects. Am trying the following code but does not work:

for column in df.columns:
    column = Asset (column)

I also tried the same thing with df.columns converted into a list of strings.

Edit My goal is to create one object for each column bearing the same name as the column. In this way, the object will possess the content of the column such as price automatically. The class is defined as:

class Asset:
    def __init__(self, name):
        self.name = name
        self.price = df[name]
        self.pct = self.price.pct_change()
st19297
  • 521
  • 1
  • 5
  • 18

1 Answers1

3

Reassigning columns just means you are changing the object that the variable references, it does not imply that the original df.columns will be updated.

I'd recommend using a list comprehension and assigning the result back:

df.columns = [Asset(x) for x in df.columns]

Based on your edit,

asset = [Asset(x) for x in df.columns]

Or,

asset = {x : Asset(x) for x in df.columns}
cs95
  • 379,657
  • 97
  • 704
  • 746
  • Thanks, but I think I was not clear. Will you please see the edit? – st19297 Oct 21 '17 at 23:10
  • @st19297 Why won't `assets = [Asset(x) for x in df.columns]` work? – cs95 Oct 21 '17 at 23:11
  • It will work but gives me a list of objects. How can I have the individual objects in the namespace rather than a list? Sorry, I'm a coding beginner – st19297 Oct 21 '17 at 23:19
  • @st19297 See this link: https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables Short answer is, you can't, and you shouldn't. Use a dictionary instead. See my final edit. – cs95 Oct 21 '17 at 23:29