• P高阶_(pandas入门)


    pandas 是做什么的

    
    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    #参考'https://www.pypandas.cn/'
    import pandas as pd
    import numpy as np
    Pandas 适用于处理以下类型的数据:
    
    与 SQL 或 Excel 表类似的,含异构列的表格数据;
    有序和无序(非固定频率)的时间序列数据;
    带行列标签的矩阵数据,包括同构或异构型数据;
    任意其它形式的观测、统计数据集,数据转入 Pandas 数据结构时不必事先标记。
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    处理数据

    '一维数据(Series),二维数据(DataFrame)'
    'DataFrame 是 Series 的容器,Series 则是标量的容器'
    
    • 1
    • 2

    数据结构

    "Series"
    'Series是带标签的一维数组,可存储整数、浮点数、字符串、Python 对象等类型的数据。
    轴标签统称为索引'
    data = 18
    index = 1,  # 这里应该是个元祖或者数组等,不能为字符串或者数字
    res = pd.Series(data=data, index=index)
    print(res)
    """
    1    18
    dtype: int64
    """
    
    data = 18
    index = 1, 2, 3, 4  # 这里应该是个元祖或者数组等,不能为字符串或者数字
    res = pd.Series(data=data, index=index)
    print(f'data是标量,索引为多个-->')
    print(res)
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    data类型

      """
       标量
        多维数组
        PYTHON字典
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5

    多维数组

    data = [18, 19]
    index = [1, 2, ]
    res = pd.Series(data=data, index=index)
    print(f'data是多维数组-->')
    print(res)
    
    '不指定索引'
    data = [18, 19]
    
    res = pd.Series(data=data)  # [0,.....,len(data)-1]
    print(f'不指定索引-->')
    print(res)
    """
    0    18
    1    19
    dtype: int64
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    字典

    'data 为字典,且未设置 index 参数时,如果 Python 版本 >= 3.6 且 Pandas 版本 >= 0.23,Series 按字典的插入顺序排序索引。'
    data = {"b小A": "吃饭", "a小B": "没吃饭"}
    res = pd.Series(data=data)
    print(f'data是字典-->')
    print(res)
    """
    b小A     吃饭
    a小B    没吃饭
    dtype: object
    """
    
    res = pd.Series(data=data, index=["a小B", "B小a"])
    print(f'有索引有字典取值-->')
    print(res)
    """
    a小B    没吃饭
    B小a    NaN
    dtype: object
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    Series 类似多维数组

    res = pd.Series(["A", "B", "C"], index=['小A', '小B', '小C'])
    '索引'
    print(f'索引2-->')
    print(res[2])  # C
    
    print(f'索引[0:2]-->')
    print(res[:2])
    """
    小A    A
    小B    B
    dtype: object
    """
    
    # Series 是扩展数组 (opens new window),Series.to_numpy() 返回的是 NumPy 多维数组。
    'Series.array用于提取 data数据、数组。'
    
    res_array = res.array
    print(f'array用于提取数组')
    print(res_array)
    """
    
    ['A', 'B', 'C']
    Length: 3, dtype: object
    """
    
    res_li = res.tolist()  # python 原生数组
    print(res_li)  # ['A', 'B', 'C']
    res_numpy = res.to_numpy()  # NumPy 多维数组。
    print(res_numpy)  # ['A' 'B' 'C']
    
    '取索引'
    res_index = res.get("小D", )
    print(res_index)  # None
    res_index = res.get("小D", np.nan)
    print(res_index)  # nan
    
    "加减乘除"
    '最好用标量或者数值'
    print(res + res)
    print(res * 2)
    print("**************")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    DataFrame

    """
    DataFrame 是由多种类型的列构成的二维标签数据结构,类似于 Excel 、SQL 表,或 Series 对象构成的字典。
    DataFrame 是最常用的 Pandas 对象,与 Series 一样,DataFrame 支持多种类型的输入数据:
    
    一维 ndarray、列表、字典、Series 字典
    二维 numpy.ndarray
    结构多维数组或记录多维数组(opens new window)
    Series
    DataFrame
    
    除了数据,还可以有选择地传递 index(行标签)和 columns(列标签)参数。
    传递了索引或列,就可以确保生成的 DataFrame 里包含索引或列。Series 字典加上指定索引时,
    会丢弃与传递的索引不匹配的所有数据。
    没有传递轴标签时,按常规依据输入数据进行构建
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    字典生成

    '生成的索引是每个 Series 索引的并集。先把嵌套字典转换为 Series。如果没有指定列,DataFrame 的列就是字典键的有序列表'
    '对比Seriies和DataFrame'
    data = {"name": pd.Series(["A", "B", "C"], index=['小A', '小B', '小C']),
            "name1": pd.Series(["A", "B", "C"], index=['小A', '小B', '小C'])
            }
    res_dict = pd.DataFrame(data)
    #
    print(res_dict)
    print(1111111111111)
    
    res = pd.Series(["A", "B", "C"], index=['小A', '小B', '小C'])
    print(res)
    """
    小A    A
    小B    B
    小C    C
    dtype: object
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    多维数组

    #多维数组字典、列表字典生成 DataFrame
    
    data = {'one': [1., 2., 3., 4.], 'two': [4., 3., 2., 1.]}
    res = pd.DataFrame(data)
    print(res)
    """
       one  two
    0  1.0  4.0
    1  2.0  3.0
    2  3.0  2.0
    3  4.0  1.0
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    结构多维数组

    # 用结构多维数组或记录多维数组生成 DataFrame
    data = np.zeros((2,), dtype=[('A', 'i4'), ('B', 'f4'), ('C', 'a10')])
    '[(0, 0., b'') (0, 0., b'')]'
    data[:] = [(1, 2., 'Hello'), (2, 3., "World")]  # 填充
    res = pd.DataFrame(data, index=['first', 'second'])
    print("列表嵌元祖,修改索引")
    print(res)
    
    """
            A    B         C
    first   1  2.0  b'Hello'
    second  2  3.0  b'World'
    """
    res = pd.DataFrame(data, columns=['C', 'A', 'B'])
    print("列表嵌元祖,修改列名称")
    print(res)
    """
              C  A    B
    0  b'Hello'  1  2.0
    1  b'World'  2  3.0
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    列表字典

    '用列表字典生成 DataFrame'
    data = [{'a': 1, 'b': 2, 'c': 3}, {'a': 5, 'b': 10, 'c': 20}]
    res = pd.DataFrame(data, index=['first', 'second'])
    print("列表嵌字典,修改索引")
    print(res)
    """
            a   b     c
    first   1   2   3
    second  5  10  20.0
    """
    res = pd.DataFrame(data, columns=['a', 'b', 'c'])
    print("列表嵌字典,修改列名称")
    print(res)
    """
       a   b   c
    0  1   2   3
    1  5  10  20
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    DataFrame.from_dict

    '收字典组成的字典或数组序列字典'
    res = pd.DataFrame.from_dict(dict([('A', [1, 2, 3]), ('B', [4, 5, 6])]))
    print("DataFrame.from_dict")
    print(res)
    """
       A  B
    0  1  4
    1  2  5
    2  3  6
    """
    
    '把 orient 参数设置为 index, 即可把字典的键作为行标签'
    res = pd.DataFrame.from_dict(dict([('A', [1, 2, 3]), ('B', [4, 5, 6])]),
                                 orient='index', columns=['one', 'two', 'three'])
    
    print("index变成orient")
    print(res)
    """
       one  two  three
    A    1    2      3
    B    4    5      6
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    DataFrame.from_records

    '元祖'
    
    data = np.zeros((2,), dtype=[('A', 'i4'), ('B', 'f4'), ('C', 'a10')])
    res_tuple = pd.DataFrame({('a', 'b'): {('A', 'B'): 1, ('A', 'C'): 2},
                              ('a', 'a'): {('A', 'C'): 3, ('A', 'B'): 4},
                              ('a', 'c'): {('A', 'B'): 5, ('A', 'C'): 6},
                              ('b', 'a'): {('A', 'C'): 7, ('A', 'B'): 8},
                              ('b', 'b'): {('A', 'D'): 9, ('A', 'B'): 10}})
    print("元祖")  # 。。。。
    print(res_tuple)
    
    """
           a              b      
           b    a    c    a     b
    A B  1.0  4.0  5.0  8.0  10.0
      C  2.0  3.0  6.0  7.0   NaN
      D  NaN  NaN  NaN  NaN   9.0
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    提取、添加、删除列

    re

    s = pd.DataFrame.from_dict(dict([('A', [1, 2, 3]), ('B', [4, 5, 6])]),
                                 orient='index', columns=['one', 'two', 'three'])
    print("提取")
    print(res["one"])
    
    res['three'] = res['one'] * res['two']
    res['flag'] = res['one'] > 2  # 用法好奇怪--
    print("这是相乘赋值")
    print(res)
    """
       one  two  three   flag
    A    1    2      2  False
    B    4    5     20   True
    """
    
    del res['two']  # 删除第二列
    three = res.pop('three')  # 删除第三列
    print("删除二三列")
    print(res)
    
    """
       one   flag
    A    1  False
    B    4   True
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    添加

    '可以插入原生多维数组,但长度必须与 DataFrame 索引长度一致'
    
    res = res.insert(1, 'bar', res['one'])
    print("插入")
    print(res)
    """
    one  bar   flag  foo  one_trunc
    a  1.0  1.0  False  bar        1.0
    b  2.0  2.0  False  bar        2.0
    c  3.0  3.0   True  bar        NaN
    d  NaN  NaN  False  bar        NaN
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    方法链

    '用方法链分配新列'
    dfa = pd.DataFrame({"A": [1, 2, 3],
                        "B": [4, 5, 6]})
    dfa.assign(C=lambda x: x['A'] + x['B'],
               D=lambda x: x['A'] + x['C'])
    print("后面等于前面相加")
    print(dfa)
    
    "第二个表达式里,x['C'] 引用刚创建的列,与 dfa['A'] + dfa['B'] 等效。"
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    索引

    索引/选择'
    
    """
    索引基础用法如下:
    
    操作                 句法             结果
    选择列                df[col]            Series
    用标签选择行         df.loc[label]  Series
    用整数位置选择行       df.iloc[loc]   Series
    行切片                df[5:10]       DataFrame
    用布尔向量选择行       df[bool_vec]   DataFrame
    
    """
    df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
                      index=['cobra', 'viper', 'sidewinder'],
                      columns=['max_speed', 'shield'])
    print('初始化值')
    print(df)
    """
                max_speed  shield
    cobra               1       2
    viper               4       5
    sidewinder          7       8
    """
    res = df.loc['viper']
    
    print("loc输出一行值")
    print(res)
    """
    max_speed    4
    shield       5
    Name: viper, dtype: int64
    """
    res = df.iloc[0]
    
    print("iloc输出一列值")
    print(res)
    """
    max_speed    1
    shield       2
    Name: cobra, dtype: int64
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    转置

    "类似于多维数组,T 属性(即 transpose 函数)可以转置 DataFrame:"
    
    index = pd.date_range('1/1/2000', periods=8)  # 参源码,日期
    print("索引")
    print(index)
    df = pd.DataFrame(np.random.randn(8, 3), index=index, columns=list('ABC'))
    print("转置前的")
    print(df)
    print("转置后的")
    print(df[:5].T)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    控制台打印

    # res = pd.DataFrame(data=5,index=list([i for i in range(5)]))
    ''
    res = pd.DataFrame({"ONE": pd.Series(data=5, index=[i for i in range(5)]),
                        "TWO": pd.Series(data=6, index=[1, 2, 3, 4, 5, 6])})
    print("DataFrame用字典创建")
    print(res)
    """
       ONE  TWO
    0  5.0  NaN
    1  5.0  6.0
    2  5.0  6.0
    3  5.0  6.0
    4  5.0  6.0
    5  NaN  6.0
    6  NaN  6.0
    """
    print("主要信息")
    print(res.info())
    """
    
    Int64Index: 7 entries, 0 to 6
    Data columns (total 2 columns):
    Column  Non-Null Count           Dtype  
    ---     ------   --------------  -----  
     0      ONE      5 non-null      float64
     1      TWO      6 non-null      float64
    dtypes: float64(2)
    memory usage: 168.0 bytes
    None
    """
    
    '如果行太宽,指定行宽数值,默认值为 80'
    pd.set_option('display.max_colwidth', 30)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
  • 相关阅读:
    准备了 185 万养老金
    sublime_text_4126_x64 激活及安装
    VSCode-更改系统默认路径
    模拟量开关量防抖算法(模拟量超限报警功能块)
    mysql两阶段提交
    git_note
    国内主流企业级低代码开发平台有哪些?
    Axios
    二、Linux 文件与目录结构、VI/VIM 编辑器(重要)
    【SQL语法与数据库】
  • 原文地址:https://blog.csdn.net/wuhaotongxue/article/details/126374774