Numpy(Numerical Python)是一个开源的Python科学计算库,用于快速处理任意维度的数组。 Numpy支持常见的数组和矩阵操作。对于同样的数值计算任务,使用Numpy比直接使用Python要简洁的多。 Numpy使用ndarray对象来处理多维数组,该对象是一个快速而灵活的大数据容器。 NumPy提供了一个N维数组类型ndarray,它描述了相同类型的“items”的集合。这里的相同类型的item是指每一列的数据类型要一致,不同列不一定。有点像关系表那种。
Numpy 提供了两个基本的对象:
ndarray:存储数据的多维数组
ufunc:对数组进行处理的函数。
ndarray 支持一维到三维的数据结构
ndarray 对数据向量化,利用隐式逐元素的广播机制进行算术、逻辑、位运算、函数调用
# 导入 numpy 库, 约定俗成别名为 np import numpy as np np.array([1, 2, 3]) np.array((1, 2, 3)) # 同上 # array([1, 2, 3]) np.array(((1, 2),(1, 2))) np.array(([1, 2],[1, 2])) # 同上
array([[1, 2],
[1, 2]])
使用函数创建:数据生成
np.arange(10) # 10个, 不包括10,步长为 1 np.arange(3, 10, 0.1) # 从 3 开始到时,步长为 0.1 # 从 2.0 开始到 3.0,生成均匀的 5 个值,不包括终终值 3.0 np.linspace(2.0, 3.0, num=5, endpoint=False) # 返回一个 6x4 的随机数组,float 型 np.random.randn(6, 4) # 指定范围指定形状的数组,整型 np.random.randint(3,7,size=(2, 4)) # 创建从0到20随机的5个数组 np.random.randint(0, 20, 5) # array([ 9, 10, 14, 6, 14]) # 创建值为 0 的数组 np.zeros(6) # 6个浮点 0. np.zeros((5, 6), dtype=int) # 5 x 6 整型 0 np.ones(4) # 同上 np.empty(4) # 同上 # 创建一份和目标结构相同的 0 值数组 np.zeros_like(np.arange(6)) np.ones_like(np.arange(6)) # 同上 np.empty_like(np.arange(6)) # 同上 np.arange(4).repeat(4) # 将4个值依次重复四次,共16个 np.full((2,4), 9) # 两行四列值全为 93 类型
np.int64 # 有符号 64 位 int 类型 np.float32 # 标准双精度浮点类型 np.complex # 由128位的浮点数组成的复数类型 np.bool # TRUE 和 FALSE 的 bool 类型 np.object # Python 中的 object 类型 np.string # 固定长度的 string 类型 np.unicode # 固定长度的 unicode 类型 np.NaN # np.float 的子类型 np.nan # np 所有数据类型 np.sctypeDict # np.typeDict 将弃用4 数组信息
n.shape # 数组的形状, 返回值是一个元组 n.shape = (4, 1) # 改变形状 a = n.reshape((2,2)) # 改变原数组的形状创建一个新的 n.dtype # 数据类型 n.ndim # 维度数 n.size # 元素数5 计算
两个数组间的操作总是应用在每个元素上的。
np.array( [10,20,30,40] )[:3] # 支持类似列表的切片 a = np.array( [10,20,30,40] ) b = np.array( [1, 2, 3, 4] ) a+b # array([11, 22, 33, 44]) 矩阵相加 a-1 # array([ 9, 19, 29, 39]) 4*np.sin(a) # 以下举例数学函数,还支持非常多的数据函数 a.max() # 40 a.min() # 10 a.sum() # 100 a.std() # 11.180339887498949 a.all() # True a.cumsum() # array([ 10, 30, 60, 100]) b.sum(axis=1) # 多维可以指定方向 np.negative(-1) # 1 相反数6 逻辑
x = 10 np.where(x>0, 1, 0) # array(1) np.logical_and(x>0, x>5) # True np.logical_or(x>0, x<5) # True np.logical_not(x>5) # False np.logical_xor(x>5, x==0) # 异或 True7 集合
# 输出x和y的交集 np.intersect1d(x,y) # 输出在x中不在y中的元素 np.setdiff1d(x,y) # 输出x和y的并集 np.union1d(x,y) # 输出x和y的异或集 np.setxor1d(x,y)8 合并
# 以下方法传入的是一个 *arrays,如 (a1, a2, ...) np.append() # 追加, 可读性好占内存大 np.stack() np.dstack() np.vstack() # 垂直合并 np.hstack() # 水平合并 np.newaxis() # 转置 np.concatenate() # 针对多个矩阵或序列的合并操作 np.split(ab, 4, axis=0) # 分隔Pandas数据结构 1 Series
Series:带标签的一维数组
#创建 s = pd.Series(data, index=index)
其中:
data 可以是 python 对象、numpy 的 ndarray 、一个标量(定值,如 8)
index 索引是轴上的一个列表,必须和 data 的长度相同,如果没有指定则自动从 0 开始,[0, …, len(data) - 1]
结构:
DataFrame 是 Pandas 定义的一个二维数据结构。
- 横向的称作行(row),我们所说的一条数据,就是指其中的一行 纵向的称作列(column),或者可以叫一个字段,是一条数据的某个值
- 第一行是表头,或者可叫字段名,类型 Python 字典里的 key,代码数据的属性
- 第一列是索引(index),就是这行数据所描述的主体,也是这条数据的关键 表头和索引在一些场景下也有称列索引和行索引的
- 行索引和列索引可能会出外多层索引的情况,后边会遇到
DataFrame由多个相同索引的Series组成
3 索引索引:行和列上的标签,默认指行索引
列索引=字段名=表头
自然索引、数字索引:行和列的0~n形式的索引
标签:行索引、列索引
轴:只在DataFrame中使用,代表方向,0表示列,1表示行
Pandas生成数据 1 导入 2 创建数据 3 生成SeriesSeries 的创建方式如下:
s = pd.Series(data, index=index)
data 可以是 python 对象、numpy 的 ndarray 、一个标量(定值,如 8)
index 索引是轴上的一个列表,必须和 data 的长度相同,如果没有指定则自动从 0 开始,[0, …, len(data) - 1]
1)列表元组
pd.Series(['a', 'b', 'c', 'd', 'e'])
pd.Series(('a', 'b', 'c', 'd', 'e'))
2)ndarray
# 由索引为 a、b.. , 五个随机浮点数数组组成 s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e']) s.index # 查看索引 s = pd.Series(np.random.randn(5)) # 未指定索引
3)字典 dict
d = {'b': 1, 'a': 0, 'c': 2}
s = pd.Series(d)
s
# 如果指定索引,则会按索引顺序,如无法与索引对应的会产生缺失值 pd.Series(d, index=['b', 'c', 'd', 'a'])
4)标量(scalar value)
pd.Series(5.) # 指定索引 pd.Series(5., index=['a', 'b', 'c', 'd', 'e'])4 生成DataFrame
结构:
df = pd.DataFrame(
data=None,
index: ‘Axes | None’ = None,
columns: ‘Axes | None’ = None,
dtype: ‘Dtype | None’ = None,
copy: ‘bool | None’ = None,
)
data: 具体数据,结构化或者同构的 ndarray、可迭代对象、字典或者 DataFrame
index: 索引,类似数组的对象,支持解包,如果没有指定会自动生成 RangeIndex (0, 1, 2, …, n)
columns: 列索引,表头,如果没有指定会自动生成 RangeIndex (0, 1, 2, …, n)
copy:bool 或者 None, 默认为 None,从输入复制数据。对于 dict 数据,默认值 None 的行为类似于 copy=True。对于 DataFrame 或 2d ndarray 输入,默认值 None 的行为类似于 copy=False。 在版本 1.3.0 的变化
和 Series 一样,DataFrame 可以由多种数据类型来定义:
一维 numpy.ndarray、字典、列表
二维 numpy.ndarray,三维及以上的不可以
结构化的 ndarray
一个或者多个 Series
一个或者多个 DataFrame 也可以定义
创建生成:
1)字典
d = {'国家': ['中国', '美国', '日本'],
'人口': [14.33, 3.29, 1.26]}
df = pd.DataFrame(d)
df
可以指定索引,会覆盖原有的索引:
df = pd.DataFrame(d, index=['a', 'b', 'c']) df
2)Series 组成的字典
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)
df
3)ndarrays 或列表组成的字典
4)同构的数组数据
5)字典和列表
6)元组组成的字典
7)由 Series 生成
8)混杂的结构
df.dtypes # 各字段的数据类型 df.team.dtype # 某个字段的类型 s.dtype # S 的类型 df.dtypes.value_counts() # 各类型有多少个字段2、常见数据类型
主要的数据类型有:
float
int
bool
datetime64[ns]
datetime64[ns, tz]
timedelta64[ns]
timedelta[ns]
category
object
string
默认的数字类型是 int64 和 float64,文字类型是 object。
object 类型是 Python 的对象,它可以是任何数据类类型,比如字符、列表、函数、json 等等,甚至可以是 Series、DataFrame。
可以使用类型测试数据的类型:
pd.api.types.is_bool_dtype(s) pd.api.types.is_categorical_dtype(s) pd.api.types.is_datetime64_any_dtype(s) pd.api.types.is_datetime64_ns_dtype(s) pd.api.types.is_datetime64_dtype(s) pd.api.types.is_float_dtype(s) pd.api.types.is_int64_dtype(s) pd.api.types.is_numeric_dtype(s) pd.api.types.is_object_dtype(s) pd.api.types.is_string_dtype(s) pd.api.types.is_timedelta64_dtype(s)



