Search code examples
pythonisolation-forest

TypeError: cannot astype a datetimelike from [datetime64[ns, UTC]] to [int32]


i am trying to run this code and getting this error .m data looks like this enter image description here

TypeError: cannot astype a datetimelike from [datetime64[ns, UTC]] to [int32]

    import numpy as np
    import pandas as pd
    import seaborn as sns
    from sklearn.ensemble import IsolationForest
    data = pd.read_csv("data.csv", parse_dates=['timestamp'])
    data['timestamp'] = data['timestamp'].astype('int')
    model=IsolationForest(n_estimators=50, max_samples='auto', contamination=float(0.1),max_features=1.0)
    model.fit(data[['timestamp','a','b','c','d','e','f','g',    'h','i','j','k']])
    data['scores']=model.decision_function(data[['timestamp','a','b','c','d','e','f','g',   'h','i','j','k']])
    data['anomaly']=model.predict(data[['timestamp','a','b','c','d','e','f','g',    'h','i','j','k']])

the table is empty


Solution

  • Try this instead:

    data['timestamp'] = data['timestamp'].astype('datetime64[s]').astype('int')
    

    It converts to seconds first and then to an int.