python 数据分析
第一章 Python 数据分析之pandas的使用
第一节: pandas --基础操作(一): Serise 、DataFrame 创建和数据选择 基础操作
第二节: pandas – 基础操作(二): DataFrame 的增删改查、排序操作等基础操作
第三节: pandas – 基础操作(三):pandas 层次化索引创建、数据选择
第二章 Python 数据分析之 时间戳操作
第二章 python 数据分析之numpy的使用
第三章 python 数据可视化之matplotlib的使用
@[TOC](文章目录)
前言
在数据分析中pandas 有着举足轻重的地位,提供了高性能、易使用的数据结构与数据分析工具。
一、pandas是什么?
示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。
二、使用步骤
1.引入库
导入pandas和numpy两个包,导入方式如下:
import numpy as np
import pandas as pd
2.对象Series、DataFrame
pandas有2个数据对象分别为Series和DataFrame,Serise为单列数据,DataFrame是为多列Serise的集合。
2.1 生成Serise
Serise是带标签的一维数组,可存储整数、浮点数、字符串、Python 对象等类型的数据。轴标签统称为索引。调用 pd.Series 函数即可创建 Series。
格式: pd.Series(data,index=index)
上述代码中,data 支持以下数据类型:
- Python 字典
- 多维数组
- 标量值(如,5)
index 是轴标签列表,不同标签可以分为如下几种情况:
- 没有指定index参数
data用值列表生成 Series 时,Pandas 默认自动生成整数索引,代码如下:
In [3]: s = pd.Series([1, 3, 5, np.nan, 6, 8])
In [4]: s
Out[4]:
0 1.0
1 3.0
2 5.0
3 NaN
4 6.0
5 8.0
dtype: float64
- 多维数组
data为多维数组,data的长度和index的长度相同
s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
# np.random.randn(5)
# Out[34]: array([-0.87399137, -0.60509713, -1.07188732, 0.93279748, 0.23194527])
s
Out[35]:
a -0.784034
b 0.302415
c -0.907291
d 0.207490
e -0.652792
dtype: float64
- 字典
se = pd.Series({
'a':1,'b':2,'c':4})
se
Out[42]:
a 1
b 2
c 4
dtype: int64
注意:
data 为字典,且未设置 index 参数时,如果 Python 版本 >= 3.6 且 Pandas 版本 >= 0.23,Series 按字典的插入顺序排序索引。之前的版本按照,series按照字母顺序排序
- 标量值
se = pd.Series(5.0 ,index=[1,2,3,4,5])
se
Out[44]:
1 5.0
2 5.0
3 5.0
4 5.0
5 5.0
dtype: float64
2.2 生成DataFrame
DataFrame 是由多种类型的列构成的二维标签数据结构,类似于 Excel 、SQL 表,或 Series 对象构成的字典。DataFrame 是最常用的 Pandas 对象,与 Series 一样,DataFrame 支持多种类型的输入数据:
- 一维 ndarray、列表、字典、Series 字典
- 二维 numpy.ndarray
- 结构多维数组或记录多维数组
- Series
- DataFrame
- 用 Series 字典或字典生成 DataFrame
生成的index是每个series的并集,如果没有指定列,dataFrame的列就是字典键的有序列表
d = {
'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(d) # 无参数结果为sereis的并集
df
Out[52]:
one two
a 1.0 1.0
b 2.0 2.0
c 3.0 3.0
d NaN 4.0
df = pd.DataFrame(d,index=['a','b','c']) # 指定index
df
Out[54]:
one two
a 1.0 1.0
b 2.0 2.0
c 3.0 3.0
df = pd.DataFrame(d,index=['a','c'],columns=['two','aa']) # 指定index columns
df
Out[56]:
two aa
a 1.0 NaN
c 3.0 NaN
- 用列表字典生成 DataFrame,index 必须和字典长度比配,否则报错。
data = [{
'a':1, 'b':2,'c':4},{
'a':4,'b':55,'d':6}]
df =<