• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
鱼市口
博客园    首页    新随笔    联系   管理    订阅  订阅
date or other data normalization general solution in pandas
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
import time
 
# of course you can use basic pandas api doing this job, but I'd prefer general solution hereby
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)
posted on 2023-05-10 23:16  鱼市口  阅读(21)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3