0 Numpy常用数据结构
- 数组的创建
import numpy as np
简单的数组创建:
np.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)
arr1 = np.array([3,4,9,-9])
arr2 = np.array([3,4,9,-9], dtype=float)
arr3 = np.array([ [1,2,3,4], [5,6,7,8], [9,10,11,12] ])
用函数创建数组:
np.arange([start,] stop[, step,], dtype=None)
arr4 = np.arange(1, 10, 1, dtype=float)
np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0 )
arr5 = np.linspace(1, 10, 10)
np.zeros(shape, dtype=float, order='C')
np.zeros([4,5])
np.ones(shape, dtype=None, order='C')
np.ones([2,3])
- 数组属性及其方法
普遍方法
arr3.ndim
arr3.shape
arr3.dtype
arr4 = arr3.astype(int)
arr3 + 1 or arr3 /2
索引、切片方法
data2 = ((8.5,6,4.1,2,0.7),(1.5,3,5.4,7.3,9),(3.2,4.5,6,3,9),(11.2,13.4,15.6,17.8,19))
arr2 = np.array(data2)
arr2[2]
arr2[2, 1]
arr2[:, 2:4]
逗号前代表行,逗号后代表列
- 数组排序
s = np.array([1,2,3,4,3,1,2,2,4,6,7,2,4,8,4,5])
np.sort(s) 升序,不支持降序
sorted(s,reverse =True) 降序
sorted(s,reverse =False) 升序
arr1 = np.array([[0,1,3],[4,2,9],[4,5,9],[1,-3,4]])
np.sort(arr1)
np.sort(arr1, axis=0) axis = 0 表示对 行 进行操作,例如在 第1列中,将0,1,2、、、行 按从小到大进行排序
np.sort(arr1, axis=1) axis = 1 表示对 列 进行操作,例如在 第1行中,讲0,1,2、、、列 按从小到大进行排序
np.argsort(s) 返回排序后的数据其在原数据中的位置
- 数组提取、搜索
s = np.array([1,2,3,4,3,1,2,2,4,6,7,2,4,8,4,5])
arr1 = np.array([[0,1,3],[4,2,9],[4,5,9],[1,-3,4]])
np.where(s>3, s, 0) s 中满足>3 条件的,保留其数值, 不满足条件的,赋值为0,返回的数据长度与s 一样
np.where(arr1>3, arr1, 0) 类似
np.extract(s>3, s) 找出符合条件的数据,只输出满足条件的数据
np.extract(arr1>3, arr1) 无论几维,只输出一行
1 Pandas常用数据结构
- series 序列
构造序列
pd.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)
copy和fastpath表示是否复制和路径
series1 = pd.Series([2.8,3.01,8.99,8.59,5.18])
series2 = pd.Series([2.8,3.01,8.99,8.59,5.18], index = ['a','b','c','d','e'], name = '这是一个测试') 自己添加索引
series3 = pd.Series({'北京':2.8,'上海':3.01,'广东':8.99,'江苏':8.59,'浙江':5.18}) 利用字典创建索引和数据
序列属性
series3.values 获取series3 的数据
series3.index 获取series3 的索引
序列索引、切片
series3[0]
series3['北京']
series3[0:2] 左闭右开
series3['北京':'江苏'] 左闭右闭
- dataframe 二维数据表结构
创建二维数据表
pd.DataFrame(data=None, index, columns, dtype, copy = False)
list1 = [['张三',23,'男'],['李四',27,'女'],['王二',26,'女']]
df1 = pd.DataFrame(list1, columns = ['姓名', '年龄', '性别']) 利用嵌套列表创建
df2 = pd.DataFrame({'姓名':['张三','李四','王二'], '年龄':[23,27,26],'性别':['男','女','女']}) 利用字典的键值对创建
arr1 = np.array([['张三',23,'男'],['李四',27,'女'],['王二', 26,'女']])
df3 = pd.DataFrame(arr1, columns = ['姓名', '年龄', '性别'], index = ['a', 'b', 'c']) 利用数组创建
dataframe 属性
df3.values 取数据值
df3.index 取行索引值
df3.columns 取列索引值
df3.dtypes 数据类型
df3.ndim 维度
df3.size 数据的个数