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

datetime struggle with a pandas dataframe

I am running the following code:

filled_df = (ts.set_index(date_col)
                 .groupby(grouping)
                 .apply(lambda d: d.reindex(
                     pd.date_range(
                         mf_heuristic(d.index, champion_end), pd.to_datetime(
                             dt.datetime.now()
                         ),
                         freq='MS')
                 )
    )
        .drop(grouping, axis=1)
        .reset_index(grouping)
        .fillna(0)

with the predefinitions:

date_col = 'timepoint'
grouping = ['Level', 'Kontogruppe']
champion_end = fc_date - pd.DateOffset(months=13)

print(champion_end)
2021-03-01 00:00:00

print(ts)
Kontogruppe  Level   timepoint    data_value
0       A   ZBFO  2020-03-01      1
1       B   ZBFO  2020-07-01      1612.59
2       A   ZBFO  2020-08-01      1046.1

print(ts.dtypes)
Kontogruppe     object
Level           object
timepoint       object
data_value         float64
dtype: object
def mf_heuristic(date, champion_end):
        
        if min(date) < champion_end:
            start_date = min(date)
        else:
            
            start_date = min(date)
        return start_date

When I run the code, I get the following error massage:

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

TypeError: Cannot compare Timestamp with datetime.date. Use ts ==
pd.Timestamp(date) or ts.date() == date instead.

for the line with the mf_heuristic function.

If I try to put before:

ts[date_col] = pd.Timestamp(ts[date_col]) 

I get the error massage:

TypeError: function missing required argument ‘year’ (pos 1)

>Solution :

Try using to_datetime:

ts[date_col] = pd.to_datetime(ts[date_col])
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