zoukankan      html  css  js  c++  java
  • Google 机器学习笔记一 Pandas简介

    这些课程的编程联系使用Pandas库来操控数据集,所以先来简单学习一下Pandas库。

    在window上安装pandas

    cmd进入Python的安装目录下的Scripts目录

    先找到Python的安装目录下的Scripts, 可以在环境变量设置中找到,比如我这里是


    Scripts

    #切换到d盘
    d: 
    #切换到Scripts目录
    cd D:PythonPython36-32Scripts

    使用pip安装pandas

    pip install pandas


    finish

    基本概念

    导入pandas库

    >>> import pandas as pd
    >>> pd.__version__
    '0.22.0'

    创建 Series

    pandas 中的主要数据结构被实现为以下两类:
    DataFrame,您可以将它想象成一个关系型数据表格,其中包含多个行和已命名的列。
    Series,它是单一列。DataFrame 中包含一个或多个 Series,每个 Series 均有一个名称。
    下面构建一个Series对象:

    >>> pd.Series(['San Francisco', 'San Jose', 'Sacramento'])
    0    San Francisco
    1         San Jose
    2       Sacramento
    dtype: object

    创建 DataFrame对象

    (1)使用dict和series创建DataFrame对象

    >>> population = pd.Series([852469, 1015785, 485199])
    >>> city_names = pd.Series(['San Francisco', 'San Jose', 'Sacramento'])
    >>> pd.DataFrame({ 'City name': city_names, 'Population': population })
           City name  Population
    0  San Francisco      852469
    1       San Jose     1015785
    2     Sacramento      485199

    (2)加载文件到DataFrame中
    下面的示例加载了一个包含加利福尼亚州住房数据的文件,read_csv读入文件,describe显示信息。

    >>> california_housing_dataframe = pd.read_csv("https://storage.googleapis.com/mledu-datasets/california_housing_train.csv", sep=",")
    >>> california_housing_dataframe.describe()
              longitude      latitude  housing_median_age   total_rooms  
    count  17000.000000  17000.000000        17000.000000  17000.000000   
    mean    -119.562108     35.625225           28.589353   2643.664412   
    std        2.005166      2.137340           12.586937   2179.947071   
    min     -124.350000     32.540000            1.000000      2.000000   
    25%     -121.790000     33.930000           18.000000   1462.000000   
    50%     -118.490000     34.250000           29.000000   2127.000000   
    75%     -118.000000     37.720000           37.000000   3151.250000   
    max     -114.310000     41.950000           52.000000  37937.000000   
    
           total_bedrooms    population    households  median_income  
    count    17000.000000  17000.000000  17000.000000   17000.000000   
    mean       539.410824   1429.573941    501.221941       3.883578   
    std        421.499452   1147.852959    384.520841       1.908157   
    min          1.000000      3.000000      1.000000       0.499900   
    25%        297.000000    790.000000    282.000000       2.566375   
    50%        434.000000   1167.000000    409.000000       3.544600   
    75%        648.250000   1721.000000    605.250000       4.767000   
    max       6445.000000  35682.000000   6082.000000      15.000100   
    
           median_house_value  
    count        17000.000000  
    mean        207300.912353  
    std         115983.764387  
    min          14999.000000  
    25%         119400.000000  
    50%         180400.000000  
    75%         265000.000000  
    max         500001.000000  

    使用DataFrame.head显示前几行记录:

    >>> california_housing_dataframe.head()
       longitude  latitude  housing_median_age  total_rooms  total_bedrooms  
    0    -114.31     34.19                15.0       5612.0          1283.0   
    1    -114.47     34.40                19.0       7650.0          1901.0   
    2    -114.56     33.69                17.0        720.0           174.0   
    3    -114.57     33.64                14.0       1501.0           337.0   
    4    -114.57     33.57                20.0       1454.0           326.0   
    
       population  households  median_income  median_house_value  
    0      1015.0       472.0         1.4936             66900.0  
    1      1129.0       463.0         1.8200             80100.0  
    2       333.0       117.0         1.6509             85700.0  
    3       515.0       226.0         3.1917             73400.0  
    4       624.0       262.0         1.9250             65500.0  

    使用DataFrame.hist快速了解一个列中值的分布

    访问数据

    使用 Python dict/list 指令访问 DataFrame 数据:

    >>> cities = pd.DataFrame({ 'City name': city_names, 'Population': population })
    >>> print(type(cities['City name']))
    <class 'pandas.core.series.Series'>
    >>> cities['City name']
    0    San Francisco
    1         San Jose
    2       Sacramento
    Name: City name, dtype: object
    >>> print(type(cities['City name'][1]))
    <class 'str'>
    >>> cities['City name'][1]
    'San Jose'
    >>> cities['City name'][0]
    'San Francisco'
    >>> cities['City name'][2]
    'Sacramento'

    操控数据

    (1)Python的基本运算指令操作

    >>> population = pd.Series([852469, 1015785, 485199])
    >>> population / 1000.
    0     852.469
    1    1015.785
    2     485.199
    dtype: float64

    (2)pandas Series 可用作 NumPy 函数的参数

    >>> population = pd.Series([852469, 1015785, 485199])
    >>> import numpy as np
    >>> np.log(population)
    0    13.655892
    1    13.831172
    2    13.092314
    dtype: float64

    (3)对于更复杂的单列转换,可以使用 Series.apply,以参数形式接受 lambda 函数,而该函数会应用于每个值。

    >>> population.apply(lambda val: val > 1000000)
    0    False
    1     True
    2    False
    dtype: bool

    (4)修改DataFrame,添加两个Series

    >>> cities['Area square miles'] = pd.Series([46.87, 176.53, 97.92])
    >>> cities['Population density'] = cities['Population'] / cities['Area square miles']
    >>> cities
           City name  Population  Area square miles  Population density
    0  San Francisco      852469              46.87        18187.945381
    1       San Jose     1015785             176.53         5754.177760
    2     Sacramento      485199              97.92         4955.055147

    索引

    Series 和 DataFrame 对象也定义了 index 属性,该属性会向每个 Series 项或 DataFrame 行赋一个标识符值。
    默认情况下,在构造时,pandas 会赋可反映源数据顺序的索引值。索引值在创建后是稳定的;也就是说,它们不会因为数据重新排序而发生改变。

    >>> population = pd.Series([852469, 1015785, 485199])
    >>> city_names = pd.Series(['San Francisco', 'San Jose', 'Sacramento'])
    >>> cities = pd.DataFrame({ 'City name': city_names, 'Population': population })
    >>> city_names.index
    RangeIndex(start=0, stop=3, step=1)
    >>> cities.index
    RangeIndex(start=0, stop=3, step=1)

    调用 DataFrame.reindex 以手动重新排列各行的顺序。例如,以下方式与按城市名称排序具有相同的效果:

    >>> cities.reindex([2, 0, 1])
           City name  Population
    2     Sacramento      485199
    0  San Francisco      852469
    1       San Jose     101578

    重建索引是一种随机排列DataFrame的绝佳方式。在下面的示例中,我们会取用类似数组的索引,然后将其传递至NumPy 的random.permutation函数,该函数会随机排列其值的位置。如果使用此重新随机排列的数组调用reindex,会导致DataFrame行以同样的方式随机排列。

    >>> import numpy as np
    >>> cities.reindex(np.random.permutation(cities.index))
           City name  Population
    0  San Francisco      852469
    2     Sacramento      485199
    1       San Jose     1015785
    >>> cities.reindex(np.random.permutation(cities.index))
           City name  Population
    0  San Francisco      852469
    2     Sacramento      485199
    1       San Jose     1015785
    >>> cities.reindex(np.random.permutation(cities.index))
           City name  Population
    1       San Jose     1015785
    0  San Francisco      852469
    2     Sacramento      485199

    每次都把cities的index拿出来放到numpy的函数中随机摇一下再返回。


    https://colab.research.google.com/notebooks/mlcc/intro_to_pandas.ipynb?hl=zh-cn

  • 相关阅读:
    【BZOJ2329】括号修复(splay)
    连接数据库
    文件锁
    带进度条的输入流
    文件对话框
    使用Scanner来解析文件
    IO流(数据流
    IO流(随机流,数组内存流
    IO流文件字符输入输出流,缓冲流
    IO流(文件字节输入输出
  • 原文地址:https://www.cnblogs.com/siucaan/p/9623198.html
Copyright © 2011-2022 走看看