0

I would like to create a variable to easily use the Adjusted Close price, which is simple for other single-worded attributes (like 'Close') but not that straightforward with Adjusted Close. How can I do the same thing I do here below with the column 'Close'?

    end = dt.datetime.now()
    start = end - dt.timedelta(weeks=104)
    stocks_list = ['COST', 'NIO', 'AMD']
    df = pdr.get_data_yahoo(stocks_list, start, end)
    Close = df.Close
    Close.head()
    
1
  • adjusted_close = df['Adjusted Close']?
    – BigBen
    Oct 6, 2022 at 16:47

1 Answer 1

1

What you are referring to here is called Attribute Access in the documentation. Near the end of the section on Attribute access, there is the following warning:

You can use this access only if the index element is a valid Python identifier, e.g. s.1 is not allowed. See here for an explanation of valid identifiers.

From the linked documentation on what a valid identifier is:

Within the ASCII range (U+0001..U+007F), the valid characters for identifiers are the same as in Python 2.x: the uppercase and lowercase letters A through Z, the underscore _ and, except for the first character, the digits 0 through 9.

Adjusted Close is not a valid python identifier (due to the space), so it will not be accessible as an attribute of your dataframe. There are also some other exceptions in the same warning that are worth reading about.

I would recommend an approach like BigBen suggests in the comments where you simply assign a local variable based on the column name as a string adjusted_close = df['Adjusted Close'].

If you are dead set on using Attribute access, you can mangle your column's name so it becomes a valid python identifier, and then you can use attribute access. From your example, this can be done with:

df.rename(columns = {"Adjusted Close" : "AdjustedClose"}, inplace = True)

Once you do this, you can access the Adjusted Close with df.AdjustedClose. I don't really recommend this approach, but it's possible.

2
  • Thank you very much! Why wouldn't you recommend the last approach? Oct 7, 2022 at 15:17
  • I personally don't recommend it because in addition to the need to mangle column names, some names can't be used at all, or would introduce subtle bugs that aren't easily caught with Python's type system. For example, if you had a column named max, there is already a DataFrame attribute named max, so Pandas would return that attribute instead of the column. I prefer to avoid accessing columns as attributes so it's clear in my code when I'm using a built-in DataFrame attribute.
    – rnorris
    Oct 7, 2022 at 15:36

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.