• python编程实用技巧


    1. 定义二维数组

    a = [[0] * 3 for i in range(3)]

    2. 求两个集合的笛卡尔积

    import itertools as it
    a = [1,2,3]
    b = [4,5,6]
    for c in it.product(a,b):
        print(c)

     3.推导式

    variable = [out_exp_res for out_exp in input_list if out_exp == 2]
        out_exp_res:  列表生成元素表达式,可以是有返回值的函数。
        for out_exp in input_list:  迭代input_list将out_exp传入out_exp_res表达式中。
        if out_exp == 2:  根据条件过滤哪些值可以。

    #example
    def squared(x):
        return x*x
    multiples = [squared(i) for i in range(30) if i % 3 is 0]
    print multiples
    # Output: [0, 9, 36, 81, 144, 225, 324, 441, 576, 729]

    4.求两序列的相关系数

    import pandas as pd
    src = r'datafill.csv'
    data = pd.read_csv(src, parse_dates=[0],index_col='TIME')
    print(data[['zhexi_in','xiaoxi_out','zhexi_add','xinhua_add','lengshuijiang_add']].corr()['zhexi_in'])
    #result
    ##zhexi_in             1.000000
    ##xiaoxi_out           0.806205
    ##zhexi_add            0.145267
    ##xinhua_add           0.165155
    ##lengshuijiang_add    0.117305
    ##Name: zhexi_in, dtype: float64

     5. 画3D图

    from matplotlib import pyplot as plt
    from matplotlib.pylab import rcParams
    rcParams['figure.figsize'] = 15, 9
    from mpl_toolkits.mplot3d import Axes3D
    
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    x = np.arange(1024)
    y = np.arange(1024)
    z = np.random.rand(1024)
    ax.scatter(x,np.zeros(1024),z,color = '#00CED1' , alpha = 0.2 , label = 'DDDDD')
    ax.plot(x,np.zeros(1024)+1,z,color = '#0567D1' , alpha = 0.2 , label = 'DDDDD')
    ax.text(0,0,0,'DDDDDD',color='r',ha='center', va='bottom', fontsize=10)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z)')
    plt.show()
    plt.close()

    6. 随机得到训练集和测试集

    from sklearn.model_selection import train_test_split
    train_x, test_x, train_y, test_y = train_test_split(x, y, test_size=0.1,random_state=self.get_random_state()) # random_state用于设置随机数种子,test_size为测试集的大小

    7.求均方误差MSE

    from sklearn.metrics import mean_squared_error
    mse = mean_squared_error(predict,test_y)

    8.一些可以解决回归问题的算法

    from sklearn import linear_model as lm
    import xgboost as xgb
    from sklearn import ensemble
    def
    set_models(self): self.models = { 'BayesianRidge':lm.BayesianRidge(), 'LinearRegression':lm.LinearRegression(), 'Ridge':lm.Ridge(), 'Lasso':lm.Lasso(), 'LassoLars':lm.LassoLars(), 'GradientBoostingRegressor':ensemble.GradientBoostingRegressor(), 'BaggingRegressor':ensemble.BaggingRegressor(), 'RandomForestRegressor':ensemble.RandomForestRegressor(criterion='mse'), 'ensemble.AdaBoostRegressor':ensemble.AdaBoostRegressor(), 'XGBRegressor':xgb.XGBRegressor(n_estimators=230, min_child_weight=2) }

    9.获取字符的assic码

    ord('a')
    #结果为97

    10.在本地建文件夹

    import os
    if not os.path.exists(self.result_path + name +'/non_add_rain/'):
                        os.makedirs(self.result_path + name +'/non_add_rain/')
     listglob = glob.glob(r"/home/xxx/picture/*.png") #通配符,找到所有满足条件的文件
     file_name = os.path.basename(r"/home/xxx/picture/hello.png") #file_name = 'hello.png'
     prefix,suffix = os.path.splitext(file_name) #'hello'   'png'
     
  • 相关阅读:
    java学习疑问
    HTTP method GET is not supported by this URL
    详解ListView分页(带图片)显示用法案例
    MySQL 字段数据类型/长度
    getRequestDispatcher()与sendRedirect()的区别
    Codeforces Round #754 (Div. 2) D,E 题解
    CCPC2019 Harbin Site B.Binary Numbers
    2020 EC Final D. City Brain
    [USACO15JAN]Grass Cownoisseur G
    CF1295F Good Contest
  • 原文地址:https://www.cnblogs.com/54hys/p/10513023.html
Copyright © 2020-2023  润新知