Enola Henrotin
Enola Henrotin

Reputation: 55

Extract the position of one date in a dataframe

I'm looking for a way to cut my dataframe at one precise date, so I thought about enter this date in my code, and then, extract the position of where it is and then just slice my dataframe with that position as the end of the df.

Here is my code :

import pandas as pd 
import numpy as np 
from pathlib import Path 
import re  
from datetime import date

DAY_CHOOSEN = pd.DataFrame() 
out=pd.DataFrame()
temp = read_csv("data.csv",sep=";")
DAY_CHOOSEN=date(day=23,month=4,year=year_)
for row in temp[0] : 
   if row [0] == DAY_CHOOSEN : 
       index=row
temp=temp[:index]              
out = pd.merge(out,temp,left_index = True, right_index = True,how = 'outer')    
print(f"{name} a ete traite")

But when I launch my code, I obviously have this error :

Traceback (most recent call last):
  File "C:\Users\E31\Documents\cours\stage_dossier\projet_python\extract_period.py", line 40, in <module>
    if row ['dte_'+str(year_)] == DAY_CHOOSEN :
TypeError: 'Timestamp' object is not subscriptable

Here is a link to download an example of my file. https://www.mediafire.com/file/86xw88k8b1f530s/data.csv/file How can I manage with this ? Thank you for your help !

Upvotes: 0

Views: 146

Answers (1)

FObersteiner
FObersteiner

Reputation: 25664

You can easily slice your data based on a certain date if you parse the column that contains the date information to datetime datatype. Ex:

import pandas as pd

df = pd.read_csv(filename, sep=';', decimal=',')

# to datetime
df['dte_1981'] = pd.to_datetime(df['dte_1981'], dayfirst=True)

# now you can slice your df...
DAY_CHOOSEN = pd.Timestamp('1981-04-23')
df_select = df[df['dte_1981'] > DAY_CHOOSEN]


df_select
      dte_1981 res_1981    SQ_x
113 1981-04-24       2.5  -2.05
114 1981-04-25       2.5  -2.05
115 1981-04-26       2.5  -2.05
....

Upvotes: 2

Related Questions