0

I have a list of dates in string format like this:

dates=['2021-06-23','2021-06-22','2021-06-18']

I'm trying to gather data for a stock (cl=f//crude oil) using yfinance library. Here is the code uptil now:
I'm trying to return the data for dates in the dates(list).

import yfinance as yf
import pandas as pd

key='cl=f'

dates=['2021-06-23','2021-06-22','2021-06-18','2021-06-17']

data=yf.Ticker(key).history(period='max')
data['date']=data.index
data.reset_index(drop=True,inplace=True)
#rearranging columns
cols=['Open', 'High', 'Low', 'Close', 'Volume', 'Dividends', 'Stock Splits','date']
cols=cols[-1:]+cols[:-1]
data=data[cols]
print(data.head())

I've tried using:

data=data[(str(data['date'])== i for i in dates)]

It gave me the following error:

KeyError: "None of [Index([False, False, False, False], dtype='object')] are in the [columns]"

Why am I getting this error?
Some assistance required.

aaryansh
  • 1
  • 1
  • 1
    Try `data[data['date'].astype(str).isin(dates)]`, Make sure doing `astype(str)` has the values in the same format that in `dates` list. I just tested it and it works fine. You don't even need `astype(str)` because the columns are already as string. – ThePyGuy Jun 28 '21 at 15:02
  • @Don'tAccept Thanks! this helped , I tried changing each of the value in the 'date' column to string earlier but it still didnt help, thanks! – aaryansh Jun 28 '21 at 15:06
  • `data = data[data['date'].isin(dates)]` astype str is not necessary. – Henry Ecker Jun 28 '21 at 15:08

2 Answers2

0

Try:

data = data[data["date"].isin(dates)]
not_speshal
  • 22,093
  • 2
  • 15
  • 30
-1
data=data['date'].astype(str).isin(dates)

worked. Answered by- @Don'tAccept (1st comment)

aaryansh
  • 1
  • 1