0

I have a DataFrame that looks like this:

           Date   Adj Close                   Close                    High  ...         Low                    Open                Volume           
                       AAPL         SPY        AAPL         SPY        AAPL  ...        AAPL         SPY        AAPL         SPY      AAPL        SPY
2050 2023-02-28  147.410004  396.260010  147.410004  396.260010  149.080002  ...  146.830002  396.149994  147.050003  397.230011  50547000   96438600
...

How do I get a DataFrame with just the Close of AAPL and the Close of SPY?

I tried this but I get an error:

column_names = ['Close' + ticker, 'Close SPY']
data = data[column_names]

raise KeyError(f"{keyarr[cmask]} not in index")
KeyError: "['CloseAAPL' 'Close SPY'] not in index"
Ivan
  • 7,448
  • 14
  • 69
  • 134
  • 1
    Please see [How to make good reproducible pandas examples](https://stackoverflow.com/q/20109391/4450498) and provide a reproducible way for us to ingest your DataFrame ourselves. Are those column labels a MultiIndex? – L0tad Mar 13 '23 at 22:53

1 Answers1

1

It's hard to say for sure without access to your DataFrame, but my guess is that your column labels are a pandas MultiIndex, in which case treating each column name as a single string (i.e. "Close SPY" will not work (even if you did have a space in your 'CloseAAPL' string, which 'Close'+ticker does not create). Instead, try column names = [("Adj Close", ticker), ("Close", "SPY")] or something similar.

L0tad
  • 574
  • 3
  • 15