将多个列转换为epoch时间戳的pandas方法

我正在尝试将以下几列转换为epoch时间戳,以便为机器学习做准备。我的csv文件的其余部分包含字符串,因此我认为这是最好的方法。我尝试创建一个numpy数组并使用datetime等进行转换,但没有成功。我有4列需要从“dd/mm/yyyy”格式转换为epoch时间戳?我尝试了这种方法

epoch_time = (1/2/2017 - datetime(1/1/1970)).total_seconds()

但是我有4列需要转换,非常感谢您的帮助

state                       objectcar_model                   objectcar_make                    objectcar_year                   float64drive_date                  objectid                           int64register_date       datetime64[ns]profile_date                objectadd_profile_date            objectdtype: objectid: 23432   state:ohio  car_model:ford car_make:fusion car_year:2016 drive_date:1/1/2017 register_date:12/25/2016 profile_date:12/25/2016 add_profile_date: 12/25/2016

回答:

尝试如下方法:

源数据框:

In [173]: dfOut[173]:      id state car_model car_make  car_year drive_date register_date profile_date add_profile_date0  23432  ohio      ford   fusion      2016   1/1/2017    2016-12-25   12/25/2016       12/25/2016In [174]: df.dtypesOut[174]:id                           int64state                       objectcar_model                   objectcar_make                    objectcar_year                     int64drive_date                  objectregister_date       datetime64[ns]profile_date                objectadd_profile_date            objectdtype: object

让我们选择包含date的列:

In [175]: date_cols = df.columns[df.columns.str.contains('_date')]In [176]: date_colsOut[176]: Index(['drive_date', 'register_date', 'profile_date', 'add_profile_date'], dtype='object')

首先将“字符串”日期转换为Pandas的datetime格式,然后转换为UNIX epoch时间戳

In [177]: for col in date_cols:     ...:     if df.dtypes.loc[col] == 'object':     ...:         df[col] = pd.to_datetime(df[col])     ...:     df[col] = df[col].astype(np.int64) // 10**9     ...:In [178]: dfOut[178]:      id state car_model car_make  car_year  drive_date  register_date  profile_date  add_profile_date0  23432  ohio      ford   fusion      2016  1483228800     1482624000    1482624000        1482624000In [179]: df.dtypesOut[179]:id                   int64state               objectcar_model           objectcar_make            objectcar_year             int64drive_date           int64register_date        int64profile_date         int64add_profile_date     int64dtype: object

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注