资讯详情

python数据分析-pandas学习

文章目录

  • 一、pandas环境的搭建
    • 1.pandas 简介
    • 2.pandas安装和调用
  • 二、pandas学习
    • 1.pandas简介
    • 2.pandas学习资源
    • 3.pandas核心数据结构
    • 4.Series
      • a.Series定义
      • b.Series的创建
      • c.Series访问中数据
      • d.Series的常用属性
    • 5.DataFrame
      • a.DataFrame定义
      • b.DataFrame创建
      • c.DataFrame常用属性
      • d.操作核心数据结构
        • 显示索引,列
        • 索引选择
        • 复合索引
        • 列操作
          • 列访问
          • 列添加
          • 列删除
        • 行操作
          • 行访问
          • 行添加
          • 行删除
        • 数据对齐
        • DataFrame的运算
        • DataFrame的转置
      • e.apply函数
      • f.排序
      • g.数据合并
        • concat
        • merge
        • join
    • 6.Pandas描述性统计分析
      • a.分组聚合
      • b.透视表与交叉表
      • c.汇总数据描述
      • d.索引的最小值/最大值
      • e.描述性统计数值特征
      • f.类别特征的描述性统计
      • g.方法摘要
    • 7.数据加载
      • a.读取csv文件
      • b.处理JSON
      • c.读取文本文件
    • 8.数据清洗
      • a.重复值的检测和处理
        • duplicated()函数
      • b.缺失值的检测和处理
        • 1)删除法
        • 2)替换法
        • 3)插值法
      • c.异常值的检测和处理
        • 1)简单统计分析
        • 2)3σ原则
        • 3)箱线图分析
    • 9.pandas可视化
      • a.基本绘图
        • Series数据可视化
        • DataFrame数据可视化
      • b.高级绘图

一、pandas环境的搭建

1.pandas 简介

Python Data Analysis Library

pandas是基于NumPy 为解决数据分析任务而创建的工具。Pandas 纳入大量库和一些标准数据模型,为大型结构化数据集的高效操作提供了工具。

pandas它提供了大量的函数和方法,使我们能够快速方便地处理数据。Python很长一段时间以来,它一直非常适合数据整理和准备,你很快就会发现它是使用的Python成为数据分析环境的重要因素 一。

pandas是python基于结构化数据的工具集numpy,图像库是matplotlib。

2.pandas安装和调用

pandas官网 :https://pandas.pydata.org/ 安装:pip install pandas 调用:import pandas as pd

二、pandas学习

1.pandas简介

Python Data Analysis Library

pandas是基于NumPy 为解决数据分析任务而创建的工具。Pandas 纳入大量库和一些标准数据模型,为大型结构化数据集的高效操作提供了工具。

pandas它提供了大量的函数和方法,使我们能够快速方便地处理数据。Python很长一段时间以来,它一直非常适合数据整理和准备,你很快就会发现它是使用的Python成为数据分析环境的重要因素 一。

pandas是python基于结构化数据的工具集numpy,图像库是matplotlib。

2.pandas学习资源

pandas官网 :https://pandas.pydata.org/

3.pandas核心数据结构

它是计算机存储和组织数据的一种方式。 通常,精心选择的数据结构可以带来更高的运行或存储效率。数据结构通常与高效的检索算法和索引技术有关。

4.Series

a.Series定义

Series可以理解为一个一维的数组,只是index这个名字可以自己改变。类似于有序字典的长度,有Index和 value。index赋值必须是list类型。

Series官方文档:https://pandas.pydata.org/docs/reference/series.html

# 创建函数 Series([data, index, dtype, name, copy, …]) 
参数名称 说明
data 数据源
index 索引,赋值必须为列表
dtype 元素数据类型
name Series的名称

b.Series的创建

import pandas as pd
import numpy as np


# 创建一个空的系列
s = pd.Series()

# 从ndarray创建一个Series
data = np.array(['张三','李四','王五','赵柳'])
s = pd.Series(data)
  # 增加index,index赋值必须是列表类型
s = pd.Series(data,index=['100','101','102','103'], name='series_name')
    
# 从字典创建一个Series,字典的键作为series的键,字典的值作为series的数据
data = { 
        'S100': '张三', 'S101': '李四', 'S102': '王五', 'S103': '赵六', 'S104': '杨七'}
s = pd.Series(data)
    
# 从标量创建一个Series
s = pd.Series(5, index=[0, 1, 2, 3])
s

c.Series中数据的访问

# 1.使用索引检索元素
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
print(s)
print(s[0]) 
print(s[[0,1,2]])
print(s[s>3])
print(s[:3])
print(s[-3:])

# 2.使用(index)标签检索数据
print(s['a'])
print(s[['a','c','d']])
print(s['a':'d'])

d.Series的常用属性

属性名称 说明
Series.index 系列的索引(轴标签)
Series.array 支持该系列或索引的数据的ExtensionArray
Series.values Series的值。根据dtype将Series返回为ndarray或类似ndarray
Series.dtype 返回基础数据的dtype对象
Series.shape 返回基础数据形状的元组
Series.nbytes 返回基础数据中的字节数
Series.ndim 返回基础数据的维数(轴数)
Series.size 返回基础数据中的元素数
Series.T 返回转置
Series.dtypes 返回基础数据的dtype对象
Series.memory_usage([index,deep]) 返回该系列的内存使用情况
Series.hasnans 如果有nans,就返回True
Series.empty 指示DataFrame是否为空,如果为空则返回True
Series.name 返回系列的名称

示例:

# 创建一个series
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'], name='series_name')

# 显示series
print(s)

print(s.index)
print(s.array)
print(s.values)
print(s.dtype)
print(s.shape)
print(s.nbytes)
print(s.ndim)
print(s.size)
print(s.T)
print(s.dtypes)
print(s.memory_usage())
print(s.hasnans)
print(s.empty)
print(s.name)

# pandas识别的日期字符串格式
dates = pd.Series(['2011', '2011-02', '2011-03-01', '2011/04/01', 
                   '2011/05/01 01:01:01', '01 Jun 2011'])
# to_datetime() 转换日期数据类型
dates = pd.to_datetime(dates)
print(dates, dates.dtype)
print(type(dates))
0   2011-01-01 00:00:00
1   2011-02-01 00:00:00
2   2011-03-01 00:00:00
3   2011-04-01 00:00:00
4   2011-05-01 01:01:01
5   2011-06-01 00:00:00
dtype: datetime64[ns] datetime64[ns]
<class 'pandas.core.series.Series'>

# 获取时间的某个日历字段的数值
print(dates.dt.day)
0    1
1    1
2    1
3    1
4    1
5    1
dtype: int64

Series.dt提供了很多日期相关操作,如下:

Series.dt.year	The year of the datetime.
Series.dt.month	The month as January=1, December=12.
Series.dt.day	The days of the datetime.
Series.dt.hour	The hours of the datetime.
Series.dt.minute	The minutes of the datetime.
Series.dt.second	The seconds of the datetime.
Series.dt.microsecond	The microseconds of the datetime.
Series.dt.week	The week ordinal of the year.
Series.dt.weekofyear	The week ordinal of the year.
Series.dt.dayofweek	The day of the week with Monday=0, Sunday=6.
Series.dt.weekday	The day of the week with Monday=0, Sunday=6.
Series.dt.dayofyear	The ordinal day of the year.
Series.dt.quarter	The quarter of the date.
Series.dt.is_month_start	Indicates whether the date is the first day of the month.
Series.dt.is_month_end	Indicates whether the date is the last day of the month.
Series.dt.is_quarter_start	Indicator for whether the date is the first day of a quarter.
Series.dt.is_quarter_end	Indicator for whether the date is the last day of a quarter.
Series.dt.is_year_start	Indicate whether the date is the first day of a year.
Series.dt.is_year_end	Indicate whether the date is the last day of the year.
Series.dt.is_leap_year	Boolean indicator if the date belongs to a leap year.
Series.dt.days_in_month	The number of days in the month.

日期运算:

# datetime日期运算
delta = dates - pd.to_datetime('1970-01-01')
print(delta, delta.dtype, type(delta))
0   14975 days 00:00:00
1   15006 days 00:00:00
2   15034 days 00:00:00
3   15065 days 00:00:00
4   15095 days 01:01:01
5   15126 days 00:00:00
dtype: timedelta64[ns] timedelta64[ns] <class 'pandas.core.series.Series'>
    
# 把时间偏移量换算成天数
print(delta.dt.days)
0    14975
1    15006
2    15034
3    15065
4    15095
5    15126
dtype: int64

通过指定周期和频率,使用date_range()函数就可以创建日期序列。 默认情况下,频率是’D’。

import pandas as pd
# 以日为频率
datelist = pd.date_range('2019/08/21', periods=5)
print(datelist)

DatetimeIndex(['2019-08-21', '2019-08-22', '2019-08-23', '2019-08-24',
               '2019-08-25'],
              dtype='datetime64[ns]', freq='D')

# 以月为频率
datelist = pd.date_range('2019/08/21', periods=5,freq='M')
print(datelist)

DatetimeIndex(['2019-08-31', '2019-09-30', '2019-10-31', '2019-11-30',
               '2019-12-31'],
              dtype='datetime64[ns]', freq='M')

# 构建某个区间的时间序列
start = pd.datetime(2017, 11, 1)
end = pd.datetime(2017, 11, 5)
dates = pd.date_range(start, end)
print(dates)

DatetimeIndex(['2017-11-01', '2017-11-02', '2017-11-03', '2017-11-04',
               '2017-11-05'],
              dtype='datetime64[ns]', freq='D')

bdate_range()用来表示商业日期范围,不同于date_range(),它不包括星期六和星期天。

import pandas as pd
datelist = pd.bdate_range('2011/11/03', periods=5)
print(datelist)

DatetimeIndex(['2011-11-03', '2011-11-04', '2011-11-07', '2011-11-08',
               '2011-11-09'],
              dtype='datetime64[ns]', freq='B')

5.DataFrame

a.DataFrame定义

DataFrame是一个类似于表格的数据类型,可以理解为一个二维数组,索引有两个维度,可更改。DataFrame具有以下特点:

  • 列可以是不同的类型
  • 大小可变
  • 标记轴(行和列)
  • 针对行与列进行轴向统计

b.DataFrame创建

​ DataFrame统一的创建形式为:

 import pandas as pd
 pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
参数名称 说明
data 数据ndarray(结构化或同类),Iterable,dict或DataFrame
index 行标签,或类似数组
columns 列标签,或类似数组
dtype 元素数据类型
copy 是否可复制

示例:

import pandas as pd

# 1.创建一个空的DataFrame
df = pd.DataFrame()
print(df)
  
# 2.从列表创建DataFrame
data = [1,2,3,4,5]
df = pd.DataFrame(data)
print(df)

# 3.从二维列表创建DataFrame
data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'],dtype=float)
print(df)

# 4.从列表嵌套字典创建DataFrame
data = [{ 
        'a': 1, 'b': 2},{ 
        'a': 5, 'b': 10, 'c': 20}]
df = pd.DataFrame(data)
print(df)


# 5.从字典创建DataFrame
data = { 
        'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data, index=['s1','s2','s3','s4'])
print(df)

# 6.从字典创建DataFrame
data = { 
        'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
        'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(data)
print(df)

c.DataFrame常用属性

属性名称 描述
DataFrame.index DataFrame的索引(行标签)
DataFrame.columns DataFrame的列标签
DataFrame.dtypes 返回DataFrame中元素的dtype
DataFrame.info 打印DataFrame的简要摘要
DataFrame.select_dtypes 根据列dtypes返回DataFrame列的子集
DataFrame.values 返回DataFrame的值,返回值为ndarry
DataFrame.axes 返回一个表示DataFrame轴的列表
DataFrame.ndim 返回一个表示轴数/数组维数的整数
DataFrame.size 返回表示此对象中元素数量的整数
DataFrame.shape 返回一个表示DataFrame维数(形状)的元组
DataFrame.memory_usage([index,deep]) 返回每列的内存使用情况(以字节为单位)
DataFrame.empty 指示DataFrame是否为空

示例:

import pandas as pd

# 创建DataFrame
data = { 
        'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data, index=['s1','s2','s3','s4'])
print(df)

# 添加score列
df['score']=pd.Series([90, 80, 70, 60], index=['s1','s2','s3','s4'])
print(df)

# 轴的列表
print(df.axes)

# 数据类型
print(df['Age'].dtype)

# 是否空DataFrame
print(df.empty)   

# 轴数
print(df.ndim)

# 元素个数
print(df.size)
12

# 行标签
print(df.index)

# 值
print(df.values)

# df的前三行
print(df.head(3)) 

# df的后三行
print(df.tail(3)) 

d.核心数据结构操作

显示索引,列

import pandas as pd

# 创建DataFrame
data = { 
        'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data, index=['s1','s2','s3','s4'])

df.index
df.columns

索引选择

操作 语法 返回值
选择列 df[col] Series
按标签选择行 df.loc[label] Series
按整数位置选择行 df.iloc[loc] Series
切片行 df[5:10] DataFrame
通过布尔向量选择行 df[bool_vec] DataFrame

复合索引

DataFrame的行级索引与列级索引都可以设置为复合索引,表示从不同的角度记录数据。

data = np.floor(np.random.normal(85, 3, (6,3)))
df = pd.DataFrame(data)
index = [('classA', 'F'), ('classA', 'M'), ('classB', 'F'), ( 

标签: s103传感器balluff

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台