0

I am working with Nifty index data and I want to slice the dataframe for visualization based on two dates. But I'm getting a type error as "TypeError: cannot do slice indexing on Int64Index with these indexers [2020-03-20 00:00:00] of type Timestamp"

Code:

stdt = pd.to_datetime('20-03-2020')   
enddt =pd.to_datetime('14-02-2020')
df['Date'] = pd.to_datetime(df['Date'])  
data=df['Date'].between_time(stdt,enddt)

df['nifty'][stdt:enddt].plot(color = "blue") 
    plt.show()

I tried using between_time and index slicing but I'm getting same error. Is there any way to slice index based on timestamp? Or please let me know the mistake in my code. Any suggestions will be really helpful.

  • Does this answer your question? [How can I slice a dataframe by timestamp, when timestamp isn't classified as index?](https://stackoverflow.com/questions/37646501/how-can-i-slice-a-dataframe-by-timestamp-when-timestamp-isnt-classified-as-ind) – LSeu Mar 16 '22 at 10:43

1 Answers1

1

Why is your end date before your start date? And the slice by timestamp, simply just filter to get the rows that are between the 2 dates:

import pandas as pd
import matplotlib.pyplot as plt

data = {
        'Date':['13-02-2020','14-02-2020','19-03-2020','20-03-2020','21-03-2020','22-03-2020'],
        'nifty':[341,253,334,54,555,236]}
df = pd.DataFrame(data)


enddt = pd.to_datetime('20-03-2020')   
stdt =pd.to_datetime('14-02-2020')
df['Date'] = pd.to_datetime(df['Date'])  
data_filtered = df.loc[df['Date'].between(stdt,enddt)]

data_filtered.plot(x='Date', y='nifty',color = "blue") 
plt.show()
chitown88
  • 27,527
  • 4
  • 30
  • 59