Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Slicing Dataframe using timestamp

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading