Python-数据科学模块Numpy、统计与分析模块Pandas

numpy概述


运行速度快(C语言编写)
功能用途:数组运算
强大的N维数组对象ndarray
广播功能函数
线性代数、傅里叶变换、随机数生成等

ndarray数组

ndarray数组:
N维数组对象(矩阵),所有元素必须是相同的类型

创建ndarray数组函数:

array:将输入数据转换为ndarray

arr=array.array('i',list(range(10)))#array第一个参数有
#b, B, u, h, H, i, I, l, L, q, Q, f or d 除u代表unicode字符外其它都要求是int 和 float
print(arr)#输出结果:array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

arange:返回一个ndarray而不是列表

print(type(np.arange(10)))#输出结果:numpy.ndarray

ones:创建一个全1数组
zeros:创建一个全0数组
empty:创建新数组
eye:创建一个N*N的单位矩阵(对角线为1,其余为0)
linspace:创建等差数组

import array
array1=array.array('i',range(10))##array第一个参数有
#b, B, u, h, H, i, I, l, L, q, Q, f or d 除u代表unicode字符外其它都要求是int 和 float
print(array1)#输出结果:array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

import numpy as np
np1=np.array(range(10))
print(np1)#array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
np2=np.zeros((3,3),dtype=np.int32)
print(np2)#[0 1 2 3 4 5 6 7 8 9]
np3=np.empty((3,3),dtype=np.int32)#发现np.empty()返回一个随机元素的矩阵,大小按照参数定义,dtype默认是float64
print(np3.dtype)#输出结果:float64
print(np3)
np4=np.eye(4)
print(np4)#创建一个N*N的单位矩阵(对角线为1,其余为0)

改变nparray形状

reshape(a, newshape[, order]) Gives a new shape to an array without changing its data.
ravel(a[, order]) Return a contiguous flattened array.
ndarray.flat A 1-D iterator over the array.属性,会改变原数组。
ndarray.flatten([order]) Return a copy of the array collapsed into one dimension.方法,不会改变原数组。
修改ndarray.shape属性 .shape · reshape() : 改变array的形态

可以通过修改shape属性,在保持数组元素个数不变的情况下,改变数组每个轴的长度。

import numpy as np

np1=np.array(range(1,10))
np2=np1.reshape((3,-1))#当某个轴的元素为-1时,将根据数组元素的个数自动计算此轴的长度
np2[0]=2
print(np1)#输出结果:[2 2 2 4 5 6 7 8 9]
print(np2)#输出结果:[[2 2 2] [4 5 6] [7 8 9]]

数组a和d其实共享数据存储内存区域,因此修改其中任意一个数组的元素都会同时修改另外一个数组的内容!

numpy中多维数组转换为一维向量 · flatten(): 复制一个一维的array出来
np1 = np.array([[1, 3, 4], [1, 2, 3], [6, 7, 8]])
print(np1.reshape(1,-1))#输出结果:[[1 3 4 1 2 3 6 7 8]]
print(np1.flatten(order='C'))  # 输出结果:[1 3 4 1 2 3 6 7 8]
print(np1.flatten(order='A'))  # 输出结果:[1 3 4 1 2 3 6 7 8]
print(np1.flatten(order='K'))  # 输出结果:[1 3 4 1 2 3 6 7 8]
print(np1.flatten(order='F'))  # 输出结果:[1 1 6 3 2 7 4 3 8]
print(np1.resize((1,9)))#输出结果:None
print(np1)#输出结果:[[1 3 4 1 2 3 6 7 8]]
要注意的是reshape(返回?)后的数组不是原数组的复制,reshape前后的数组指向相同的地址(只是维度重新定义了一下) 也可以用flatten函数将高维数组转化为向量,和reshape不同的是,flatten函数会生成原始数组的复制

resize(): 也是改变array的形态。不同的是,resize是直接修改这个对象的,而reshape则会生成一个新的对象

flatten操作只是针对规则shape的ndarray,如果是不规则的列表可以使用自定义的flatten函数
flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) in [tuple, list, np.ndarray] else [x]
a = [[1, 2], 5, [6], (7, 8), (9)]
print(flatten(a))
[1, 2, 5, 6, 7, 8, 9]

类转置操作(Transpose-like operations)

rollaxis(a, axis[, start]) Roll the specified axis backwards, until it lies in a given position.
swapaxes(a, axis1, axis2) Interchange two axes of an array.
ndarray.T Same as self.transpose(), except that self is returned if self.ndim < 2.
transpose(a[, axes]) Permute the dimensions of an array.

· swapaxes(): 将n个维度中任意两个维度(坐标轴)进行调换

· transpose(): 这个就是矩阵的转置操作

np1=np.array(range(1,10)).reshape((3,3))
#输出结果
# [[1 4 7]
#  [2 5 8]
#  [3 6 9]]
print(np1.transpose())
print(np1)
#输出结果
# [[1 2 3]
# [4 5 6]
# [7 8 9]]
npArray之切片
np1=np.array(range(1,10)).reshape((3,3))
print(np1[0:2])#取除np中的0,1行
print(np1[0:1])
print(np1[:,0:2])#取出np中的第0列和第1列
print(np1[0:2,0:2])#取出np中的0-1行,0-1列
npArray的一些函数

np.dot
对两个一维npArray进行内积,对两个多维矩阵进行相乘。

#如果处理的是一维数组,则得到的是两数组的內积
x1=np.arange(5)
x2=x1[::-1]
print(x1)
print(x2)
print(np.dot(x1,x2))
#np.dot进行两个矩阵的乘法
x1=np.arange(0,5)
y1=np.arange(0,5).reshape((5,1))
print(x1)
print(y1)
print(np.dot(x1,y1))

np.random
np.random.randn()函数
语法:
np.random.randn(d0,d1,d2……dn)
1)当函数括号内没有参数时,则返回一个浮点数;
2)当函数括号内有一个参数时,则返回秩为1的数组,不能表示向量和矩阵;
3)当函数括号内有两个及以上参数时,则返回对应维度的数组,能表示向量或矩阵;
4)np.random.standard_normal()函数与np.random.randn()类似,但是np.random.standard_normal()的输入参数为元组(tuple).
5)np.random.randn()的输入通常为整数,但是如果为浮点数,则会自动直接截断转换为整数。

#np.random
ran0=np.random.randn()#当函数括号内没有参数时,则返回一个浮点数;
ran1=np.random.randn(2)#当函数括号内有一个参数时,则返回秩为1的数组,不能表示向量和矩阵;
ran2=np.random.randn(3,3)#当函数括号内有两个及以上参数时,则返回对应维度的数组,能表示向量或矩阵;
print(ran0)
print(ran1)
print(ran2)
#输出结果:
0.15859973921689055
[ 0.06464987 -0.24977577]
[[-0.34637099  0.20233752 -0.85556197]
 [-1.12947301  0.73824811  0.37469253]
 [-1.79468238  0.06768844 -0.89569751]]

作用:
通过本函数可以返回一个或一组服从标准正态分布的随机样本值。
标准正态分布是以0为均数、以1为标准差的正态分布,记为N(0,1)。对应的正态分布曲线如下所示,即
在这里插入图片描述
标准正态分布曲线下面积分布规律是:
在-1.96~+1.96范围内曲线下的面积等于0.9500(即取值在这个范围的概率为95%),在-2.58~+2.58范围内曲线下面积为0.9900(即取值在这个范围的概率为99%).
因此,由 np.random.randn()函数所产生的随机样本基本上取值主要在-1.96~+1.96之间,当然也不排除存在较大值的情形,只是概率较小而已。
应用场景:
在神经网络构建中,权重参数W通常采用该函数进行初始化,当然需要注意的是,通常会在生成的矩阵后面乘以小数,比如0.01,目的是为了提高梯度下降算法的收敛速度。
W = np.random.randn(2,2)*0.01

np.random.rand()函数
语法:
np.random.rand(d0,d1,d2……dn)
注:使用方法与np.random.randn()函数相同
作用:
通过本函数可以返回一个或一组服从“0~1”均匀分布的随机样本值。随机样本取值范围是[0,1),不包括1。
应用:在深度学习的Dropout正则化方法中,可以用于生成dropout随机向量(dl),例如(keep_prob表示保留神经元的比例):dl = np.random.rand(al.shape[0],al.shape[1]) < keep_prob

#np.randm.rand
ran0=np.random.rand()
ran1=np.random.rand(2)
ran2=np.random.rand(2,2)
print(ran0)
print(ran1)
print(ran2)
#输出结果:
0.6398511633907039
[0.46144956 0.50363851]
[[0.28126835 0.47690064]
 [0.07190584 0.10260065]]

np.random.randint()函数
语法:
numpy.random.randint(low, high=None, size=None, dtype=’l’)
输入:
low—–为最小值
high—-为最大值
size—–为数组维度大小
dtype—为数据类型,默认的数据类型是np.int。
返回值:
返回随机整数或整型数组,范围区间为[low,high),包含low,不包含high;
high没有填写时,默认生成随机数的范围是[0,low)

#np.random.rantint
ran0=np.random.randint(2)#[0,1]
ran1=np.random.randint(0,8)
ran2=np.random.randint(0,8,size=(2,2))
print(ran0)
print(ran1)
print(ran2)
#输出结果:
0
5
[[7 0]
 [7 6]]

Pandas 概述

Pandas模块是Python用于数据导入及整理的模块,对数据挖掘前期数据的处理工作十分有用。
Pandas模块的数据结构主要有两:1、Series ;2、DataFrame ,下面将分别从这两方面介绍:

Series结构介绍

The Series is the primary building block of pandas and represents a one-dimensional labeled array based on the NumPy ndarray;
大概就是说Series结构是基于NumPy的ndarray结构,是一个一维的标签矩阵(感觉跟python里的字典结构有点像)
pandas.Series的创建

# pd.Series([list],index=[list])//以list为参数,参数为一list;index为可选参数,若不填则默认index从0开始;
# 若添则index长度与value长度相等
series1=pd.Series(list(range(3)),index=['a','b','c'])
print(series1)

#pd.Series({dict})//以一字典结构为参数
list1=list(range(5))
list2='a b c d e'.split(' ')
print(list2)
dict1=dict(zip(list2,list1))
series1=pd.Series(dict1)
print(series1)

在这里插入图片描述
pandas.Series的取值

# s[index] or s[[index的list]]
# 取值操作类似数组,当取不连续的多个值时可以以一list为参数
list1=list(range(5))
list2='a b c d e'.split(" ")
dict1=dict(zip(list2,list1))
series1=pd.Series(dict1)
print(series1[1])#取单个值:1
print(series1['b'])#取单个值:1
print(series1[['a','b']])#返回值为Series类型
print(series1[1:2])#返回值为Series类型

# head(n);.tail(n)//取出头n行或尾n行,n为可选参数,若不填默认5
list1=list(range(4))
list2='a b c d'.split(" ")
dict1=dict(zip(list2,list1))
series1=pd.Series(dict1)
print(series1.head(2))#取出series中的前两个返回Series
print(series1.tail(2))#取出series中的后两个返回Series

series中的其它属性

# Size、shape、uniqueness、counts of values
list1=list(range(4))
list2='a b c d'.split(' ')
dict1=dict(zip(list2,list1))
series1=pd.Series(dict1)
print(series1.size)
print(series1.count())# Series长度,不包括NaN
print(series1.shape)#Series的形状
print(series1.unique())# 出现不重复values值
print("====")
print(series1.value_counts())# 统计value值出现次数

加减运算

# 加运算+减运算-
# 相同index的value相加,若index并非共有的则该index对应value变为NaN
series1=pd.Series([3,4,5,6,7,8])
series2=pd.Series([0,3,4,5,6,7,8])
series3=series1-series2
print(series3)

list1=list(range(4))
list2='b c a 0'.split(' ')
dict1=dict(zip(list2,list1))
series1=pd.Series(dict1)
series2=pd.Series([1,2,3,4])
print(series1)
print(series1-series2)
DataFrame结构介绍

DataFrame unifies two or more Series into a single data structure.Each Series then represents a named column of the DataFrame, and instead of each column having its own index, the DataFrame provides a single index and the data in all columns is aligned to the master index of the DataFrame.
这段话的意思是,DataFrame提供的是一个类似表的结构,由多个Series组成,而Series在DataFrame中叫columns。
在这里插入图片描述
DateFrame的创建

# 创建
# pd.DataFrame()
# 参数:
# 1、二维array;
# 2、Series 列表;
# 3、value为Series的字典
# 注:若创建使用的参数中,array、Series长度不一样时,对应index的value值若不存在则为NaN

#1.value为list的列表
df1=pd.DataFrame(np.array([[1,3,5],[2,3,4]]))
df1.index=[0,1]
df1.columns=['a','b','c']
print(df1)
df1=pd.DataFrame([[1,2,3],[3,4,5]])
print(df1)
## 2、value为Series的列表
series1=pd.Series(np.array([1,2,3,4,5]))
series2=pd.Series(np.array([1,2,3,4,5]))
df1=pd.DataFrame([series1,series2])
print(df1)
#    0  1  2  3  4
# 0  1  2  3  4  5
# 1  1  2  3  4  5

# 3、value为Series的字典
series1=pd.Series(np.array([1,2,3,4,5]))
series2=pd.Series(np.array([1,2,3,4,5]))
df1=pd.DataFrame({
    
    'a':series1,'b':series2})
print(df1)
#    a  b
# 0  1  1
# 1  2  2
# 2  3  3
# 3  4  4
# 4  5  5

dataFrame中的属性

b.属性
b.1 .columns :每个columns对应的keys
b.2 .shape:形状,(a,b),index长度为a,columns数为b
b.3 .index;.values:返回index列表;返回value二维array
b.4 .head();.tail();

Pandas中数据选取操作

df1=pd.DataFrame({
    
    'a':[1,2,3,4],'b':[5,6,7,8],'c':[3,2,1,1]})
print(df1)

#取column操作
df1=df1[['a','b']]
print(df1[['a','b']])#返回类型是dataFrame
print(type(df1['a']))#返回类型是series


#取row操作
print(df1[0:2])#对row进行切片,返回类型是dataFrame

#iat,iloc,loc
list1=[1,2,3,4]
list2=[2,4,6,8]
df1=pd.DataFrame([list1,list2])
df1.columns='a b c d'.split()
print(df1)
#    a  b  c  d
# 0  1  2  3  4
# 1  2  4  6  8
print("========")
print(df1.iat[0,2])#输出1
print(df1.iat[0,3])#输出4

print(df1.loc[0,'a'])#输出结果:1
print(df1.iloc[0,0])#输出结果:0
# print(df1.iloc[0,'a'])#会报错
#在最后一行添加数据df.shape返回的是一个元组
df1.loc[df1.shape[0]]={
    
    'a':4,'b':8,'c':12,'d':16}
df1=df1.drop(2,axis=0)#删除指定的某行
df1=df1.loc[[1]]#返回的是pandas.core.frame.DataFrame类型
print(df1)
#dataFrame.iloc # 使用iloc时,行索引始终是df对象行的序数(eg:0,1,2,...,n-1),列索引可以是df对应列的列名,也可以是列的序数(eg:0,1,2,...,n-1);


iloc与loc的不同点

  1. 使用iloc时,行索引始终是df对象行的序数(eg:0,1,2,…,n-1),列索引可以是df对应列的列名,也可以是列的序数(eg:0,1,2,…,n-1);
    使用loc时,行列索引必须与df保持一致;因此,如果仅仅是访问数据,iloc更加灵活.

  2. 当向df对象中新加入一列,其元素为空字符串时[目的是占位], 不可通过iloc来进行赋值,使用loc则可以.

  3. 在处理大批量数据时,如果需要先向df对象插入空列,在后期再填充空列中对应位置的元素,应优先考虑使用loc而不是iloc,因为前者的访问速度比后者快几十倍!!

dataFrame的其它方法

翻转dataframe的行与列

# 翻转dataframe的行与列
list1=list('abcd')
list2=list('1234')
series1=pd.Series(np.array(list1))
series2=pd.Series(np.array(list2))
df1=pd.DataFrame([series1,series2])
print(df1)
print(df1.T)

猜你喜欢

转载自blog.csdn.net/qq_44788518/article/details/110746104