pandas初识

pandas

pandas是基于Numpy的一种工具,该工具是为解决数据分析任务而创建的,pandas纳入了大量库和一些标准的数据模型,提供了高效的操作大型数据集所需要的的工具,pandas提供了大量能使我们快速便捷地处理数据的函数和方法。

  1. 表格数据操作(增删改查)
  2. 实现多个表格的处理
  3. 数据清洗操作:缺失值、重复值、异常值、数据标准化、数据转换的操作
  4. 实现所有的excel的特殊操作:生成透视表、交叉表
  5. 完成统计分析

一、pandas的创建

    import pandas as pd

1、表结构数据,构建Dataframe

Columns:列索引 index:行索引 values:元素数据

    方式一:
    df = pd.DataFrame(
        data=[['alex', 20, '男','0831'],['tom', 30, '女', '0830'],],
        index=['a','b'],   # 可以不写,默认从0开始,也可以直接指定字符进行排序
        columns=['name', 'age', 'sex', 'class'],
    )    # 构建方法
    print(df)   # 打印数据
       name  age sex class
    a  alex   20   男  0831
    b   tom   30   女  0830
    方式二:
    df1 = pd.DataFrame(data={'name':['tom', 'alex'], 'age':[18,20], 'sex':['男','女'], 'class':['0831','0831']})
    print(df)   # 打印数据,没有指定index字符排序时,默认从0开始排序
       name  age sex class
    0  alex   20   男  0831
    1   tom   30   女  0830

二、Dataframe属性

  1. 结构:shape
    print('结构',df.shape)  # 
    结构 (2, 4)
  1. 元素个数:size
    print('元素个数',df.size)   # 
    元素个数 8
  1. 数据类型:dtypes
    print('数据类型\n', df.dtypes)  # 除了int float外其他类型全为object
    类型数据类型  
    name     object
    age       int64
    sex      object
    class    object
  1. 维度:ndim
    print('维度', df.ndim)      #  
    维度 2
  1. 列索引:columns
    print('列索引', df.columns)
    列索引 Index(['name', 'age', 'sex', 'class'], dtype='object')
  1. 行索引
    print('行索引', df.index) 
    行索引 Index(['a', 'b'], dtype='object')
  1. 数据:values
    print('数据类型', df.values)
    数据类型 
    [['alex' 20 '男' '0831']
     ['tom' 30 '女' '0830']]

三、df的查找

  1. 索引某一列值
    df1[‘name’] 一维的切法,返回的是series
    print(df1['name'])  # 切一列值的方法
    0     tom
    1    alex
  1. 切多列值的方法
    print(df1[['name', 'age']]) 
       name  age
    0   tom   18
    1  alex   20
    print(type(df1[['name', 'age']]))    # series 是一维的类型,只有一个轴
    <class 'pandas.core.series.Series'>
  1. 索引切的方法
    方法一:
    print(df[['name', 'age']][:2])    # 不能指定行进行索引
       name  age
    a  alex   20
    b   tom   30
    方式二:
    索引切的方法: df.loc[行索引名称、条件, 列的索引名称]
    print(df.loc['a', 'name']) 
    alex
    df.loc['a', ['name']]     # <class 'pandas.core.series.Series'>  行或者列,只要有一个为字符串,是一维
    df.loc[['a'], ['name']]   # <class 'pandas.core.frame.DataFrame'> 行或者列,两个参数都为列表,是二维
  1. 条件索引: bool 切片
    mask = df['age']>18  # 返回所有大于18岁的同学,返回True, False
    mask2 = df['sex'] == '女'  # 返回所有女的同学
    mask3 = mask & mask2    # 将两个mask进行结合,不能使用and,只能使用 & 逻辑与
    print(mask3)
    a    False
    b     True
    dtype: bool
    print(df.loc[mask3, :])  # 利用mask,对数据进行切片
      name  age sex class
    b  tom   30   女  0830
  1. 索引查询: iloc 【行的索引, 列的索引】 # 前闭后开
    print(df.iloc[:1, :])
       name  age sex class
    a  alex   20   男  0831

df增加方法

  1. 键值对添加列
    # df['address'] = ['北京', '上海']  两种方式,一一对应, 直接等于‘北京’,则所有数据都会变成北京
    df['address'] = '北京'
        name  age sex class address
    a   alex   20   男  0831      北京
    b    tom   30   女  0830      北京

  1. append增加行
    df_mini = pd.DataFrame(data = {
            'name':['jerry', 'make'],
            'age':[15, 18],
            'sex':['男', '女'],
            'class':['0831', '0770'],
            'address':['北京', '河南']
        }, index = ['a', 'b'])
    df4 = df.append(df_mini)
    print(df4)
    a   alex   20   男  0831      北京
    b    tom   30   女  0830      北京
    a  jerry   15   男  0831      北京
    b   make   18   女  0770      河南

五、删除方法

    axis  : 删除的行或者列
    inplace:是否修改原始表
    a = df4.drop(labels=['address', 'class'], axis=1)  # 删除列 需要使用一个变量接受
    df4.drop(labels=['a'], axis=0, inplace=True)

六、修改

切出指定数据,再进行赋值修改

    c = df4.loc[df4['name'] == 'tom', 'class']  = '有问题'
    print(c)
        name  age sex class address
    a   alex   20   男  0831      北京
    b    tom   30   女   有问题      北京
    a  jerry   15   男  0831      北京
    b   make   18   女  0770      河南

七、统计分析

  1. 延用了Numpy中的10个统计方法
    min()    	argmin()
    max()    	argmax()
    std()    	vat()
    sum()    	mean()
    cumsum()    	cumprod()

  1. pandas中的方法
    df['age'].min()
    df['age'].max()
    df['age'].argsort()

  1. 众数、非空元素、频数
    df['age'].mode()
    a    grade
    b    grade
    dtype: object
    df['age'].count()
    tom      1
    make     1
    alex     1
    jerry    1
    Name: name, dtype: int64
    df['age'].value_counts()
    name       alex
    age          20
    sex           女
    class      0830
    address      北京
    dtype: object

  1. 针对df类型
    df['age'].idxmax(axis=1)    # 横向比较
    df['age'].idxmax(axis=0)    # 纵向比较
        name  age  sex class address
    0   alex   15    女  0831      北京
    1  jerry   18    男   NaN     NaN
    2   make   20  NaN   NaN     NaN
    3    tom   30  NaN   NaN     NaN

  1. 描述describe
    df['age'].describe()
    #          age
    # count   4.00  非空数目
    # mean   20.75   平均值
    # std     6.50   标准差
    # min    15.00   最小
    # 25%    17.25   1/4
    # 50%    19.00   2/4
    # 75%    22.50   3/4
    # max    30.00   最大
    df['name'].describe()
    # count : 非空数目
    # unique: 去重之后有几个值
    # top: 众数
    # freq: 众数出现的频数

在这里插入图片描述

posted @ 2021-07-08 16:43  老酱  阅读(55)  评论(0编辑  收藏  举报