Skip to main content
 首页 » 编程设计

python之如何使用 pandas/numpy 标准化/规范化日期

2025年05月04日9yjmyzz

使用以下代码片段

import pandas as pd 
train = pd.read_csv('train.csv',parse_dates=['dates']) 
print(data['dates']) 

我加载并控制数据。

我的问题是,如何标准化/规范化数据['dates'] 以使所有元素都位于 -1 和 1 之间(线性或高斯)?

请您参考如下方法:

import pandas as pd 
import numpy as np 
from sklearn.preprocessing import MinMaxScaler 
import time 
 
def convert_to_timestamp(x): 
    """Convert date objects to integers""" 
    return time.mktime(x.to_datetime().timetuple()) 
 
 
def normalize(df): 
    """Normalize the DF using min/max""" 
    scaler = MinMaxScaler(feature_range=(-1, 1)) 
    dates_scaled = scaler.fit_transform(df['dates']) 
 
    return dates_scaled 
 
if __name__ == '__main__': 
    # Create a random series of dates 
    df = pd.DataFrame({ 
        'dates': 
            ['1980-01-01', '1980-02-02', '1980-03-02', '1980-01-21', 
             '1981-01-21', '1991-02-21', '1991-03-23'] 
    }) 
 
    # Convert to date objects 
    df['dates'] = pd.to_datetime(df['dates']) 
 
    # Now df has date objects like you would, we convert to UNIX timestamps 
    df['dates'] = df['dates'].apply(convert_to_timestamp) 
 
    # Call normalization function 
    df = normalize(df) 

示例:

我们使用 convert_to_timestamp

转换的日期对象
       dates 
0 1980-01-01 
1 1980-02-02 
2 1980-03-02 
3 1980-01-21 
4 1981-01-21 
5 1991-02-21 
6 1991-03-23 

我们可以使用 sklearn 中的 MinMaxScaler 规范化的 UNIX 时间戳

       dates 
0  315507600 
1  318272400 
2  320778000 
3  317235600 
4  348858000 
5  667069200 
6  669661200 

归一化为(-1, 1),最终结果

[-1.         -0.98438644 -0.97023664 -0.99024152 -0.81166138  0.98536228 
  1.        ]