Pandas是Python第三方库,提供高性能易用数据类型和分析工具
官网文档:http://pandas.pydata.org/pandas-docs/stable/10min.html
引入:
import pandas as pd
Pandas基于NumPy实现,常与NumPy和Matplotlib一同使用
两个数据类型:Series, DataFrame
基于上述数据类型的各类操作
库 | NumPy | Pandas |
---|---|---|
数据类型 | 基础 | 扩展 |
关注数据 | 结构表达 | 应用表达 |
维度关系 | 数据间关系 | 数据与索引间关系 |
Series类型由一组数据及与之相关的数据索引组成
Series是一维带“标签”数组
结构:data_a index_0
Series基本操作类似ndarray和字典,根据索引对齐
Series类型包括index和values两部分
Series类型的操作类似ndarray类型
Series类型的操作类似Python字典类型:
Series+ Series
Series类型在运算中会自动对齐不同索引的数据
Series对象和索引都可以有一个名字,存储在属性.name中
对获取的值进行赋值
# -*- coding: utf-8 -*-
# @File : series_demo.py
# @Date : 2018-05-19
import pandas as pd
# 创建Series对象
d = pd.Series(range(5))
print(d)
"""
0 0
1 1
2 2
3 3
4 4
dtype: int64
"""
# 计算前N项和
print(d.cumsum())
"""
0 0
1 1
2 3
3 6
4 10
dtype: int64
"""
# 自动索引
d = pd.Series([1, 2, 3, 4, 5])
print(d)
"""
0 1
1 2
2 3
3 4
4 5
dtype: int64
"""
# 自定义索引
d = pd.Series([1, 2, 3, 4, 5], index=["a", "b", "c", "d", "e"])
print(d)
"""
a 1
b 2
c 3
d 4
e 5
dtype: int64
"""
# 从标量值创建, 不能省略index
s = pd.Series(20, index=["a", "b", "c"])
print(s)
"""
a 20
b 20
c 20
dtype: int64
"""
# 从字典类型创建
s = pd.Series({"a": 1, "b": 2, "c": 3})
print(s)
"""
a 1
b 2
c 3
dtype: int64
"""
# index从字典中进行选择操作
s = pd.Series({"a": 1, "b": 2, "c": 3}, index=["c", "a", "b", "d"])
print(s)
"""
c 3.0
a 1.0
b 2.0
d NaN
dtype: float64
"""
# 从ndarray类型创建
import numpy as np
s = pd.Series(np.arange(5))
print(s)
"""
0 0
1 1
2 2
3 3
4 4
dtype: int32
"""
# 指定索引
s = pd.Series(np.arange(5), index=np.arange(9, 4, -1))
print(s)
"""
9 0
8 1
7 2
6 3
5 4
dtype: int32
"""
# Series基本操作
s = pd.Series([1, 2, 3, 4, 5], index=["a", "b", "c", "d", "e"])
# 获得索引
print(s.index)
# Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
# 获得值
print(s.values)
# [1 2 3 4 5]
# 自动索引和自定义索引并存 但不能混
print(s[0])
# 1
print(s["a"])
# 1
# 切片操作
print(s[["a", "b"]])
"""
a 1
b 2
dtype: int64
"""
# 类似ndarray类型
print(s[:3])
"""
a 1
b 2
c 3
dtype: int64
"""
print(s[s>s.median()])
"""
d 4
e 5
dtype: int64
"""
print(np.exp(s))
"""
a 2.718282
b 7.389056
c 20.085537
d 54.598150
e 148.413159
dtype: float64
"""
# 类似Python字典类型
print("b" in s)
# True
print(s.get("g", 100))
# 100
# Series类型对齐操作
a = pd.Series([1, 2, 3], index=["a", "b", "c"])
b = pd.Series([5, 6, 7, 8], index=["a", "b", "d", "e"])
print(a+b)
"""
a 6.0
b 8.0
c NaN
d NaN
e NaN
dtype: float64
"""
# Series类型name属性
s = pd.Series([1, 2, 3, 4, 5], index=["a", "b", "c", "d", "e"])
s.name="Series"
s.index.name = "索引"
print(s)
"""
索引
a 1
b 2
c 3
d 4
e 5
Name: Series, dtype: int64
"""
# Series修改
s = pd.Series([1, 2, 3, 4, 5], index=["a", "b", "c", "d", "e"])
s[0] = 666
print(s)
"""
0 666
1 2
2 3
3 4
4 5
dtype: int64
"""
s["a", "b"] = 20
print(s)
"""
a 20
b 20
c 3
d 4
e 5
dtype: int64
"""
# Series删除元素
s = pd.Series([1, 2, 3, 4, 5, 6], index=["a", "b", "c", "d", "e", "f"])
print(s)
"""
a 1
b 2
c 3
d 4
e 5
f 6
dtype: int64
"""
s1 = s.drop(["a", "b"])
print(s1)
"""
c 3
d 4
e 5
f 6
dtype: int64
"""