预处理算法_10_数学函数

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-

# <editable>

def execute():
    # <editable>
    '''
    导入模块
    '''
    import math
    import pandas as pd
    from sqlalchemy import create_engine
    '''
    连接数据库
    '''
    engine = create_engine('mysql+pymysql://root:123123qwe@127.0.0.1:3306/analysis')

    '''
    选择目标数据
    '''

    params = {
        "columns": "score",
        "method": "math.sqrt",  # "向上取整:math.ceil;绝对值:math.fabs;向下取整:math.floor;平方根:math.sqrt;返回整数:math.trunc;"
        "label": 'score'
    }
    inputs = {"table": 'test'}
    sql = 'select ' + params['columns'] + ' from ' + inputs['table']
    data_in = pd.read_sql_query(sql, engine)
    print(data_in)
    '''
    使用数学类函数
    '''
    fun = eval(params['method'])
    if data_in[params['label']].dtypes == 'float64' or data_in[params['label']].dtypes == 'int':
        data_in[params['label']] = data_in[params['label']].apply(lambda x: fun(x))
        data_out = data_in
    else:
        raise ValueError('请选择数值型数据!')

    '''
    将结果写出
    '''
    print(data_out)
    '''
    数据示例
       score
    0   80.0
    1   20.0
    2    NaN
    3    5.0
    4    4.0
    5   20.0
    float64
    0    8.944272
    1    4.472136
    2         NaN
    3    2.236068
    4    2.000000
    5    4.472136
    Name: score, dtype: float64
          score
    0  8.944272
    1  4.472136
    2       NaN
    3  2.236068
    4  2.000000
    5  4.472136

    '''

# </editable>

if __name__ == '__main__':
    execute()

 

posted @ 2021-03-03 20:11  我当道士那儿些年  阅读(81)  评论(0编辑  收藏  举报