将几列转换为纪元 pandas

Convert several columns to epoch pandas

我正在尝试将以下列转换为纪元,为机器学习做准备 我的 csv 的其余部分包含字符串,所以我假设这是最好的方法,我尝试创建一个 numpy 数组并使用datetime 等,但这不起作用我有 4 列我正在尝试从 dd/mm/yyyy 转换为纪元? 这个方法我试过了

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

但我有 4 列,我想将它们全部转换,非常感谢

state                       object
car_model                   object
car_make                    object
car_year                   float64
drive_date                  object
id                           int64
register_date       datetime64[ns]
profile_date                object
add_profile_date            object
dtype: object

id: 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

试试这个:

来源 DF:

In [173]: df
Out[173]:
      id state car_model car_make  car_year drive_date register_date profile_date add_profile_date
0  23432  ohio      ford   fusion      2016   1/1/2017    2016-12-25   12/25/2016       12/25/2016

In [174]: df.dtypes
Out[174]:
id                           int64
state                       object
car_model                   object
car_make                    object
car_year                     int64
drive_date                  object
register_date       datetime64[ns]
profile_date                object
add_profile_date            object
dtype: object

让我们 select date 列:

In [175]: date_cols = df.columns[df.columns.str.contains('_date')]

In [176]: date_cols
Out[176]: Index(['drive_date', 'register_date', 'profile_date', 'add_profile_date'], dtype='object')

首先将 "string" 日期转换为 Pandas 日期时间,然后将其转换为 UNIX 纪元

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]: df
Out[178]:
      id state car_model car_make  car_year  drive_date  register_date  profile_date  add_profile_date
0  23432  ohio      ford   fusion      2016  1483228800     1482624000    1482624000        1482624000

In [179]: df.dtypes
Out[179]:
id                   int64
state               object
car_model           object
car_make            object
car_year             int64
drive_date           int64
register_date        int64
profile_date         int64
add_profile_date     int64
dtype: object