Numpy&Pandas

Numpy

##############################Numpy##################################
import numpy as np
array = np.array([[1,2,3],
                 [2,3,4]])  #列表转化为矩阵  list2array

#--------------------------------array属性--------------------------#
print(array)
print('dim',array.ndim)  #维度
print('shape',array.shape)  #行列
print('size',array.size)  #大小

#定义type  array
a = np.array([3,45,12,43],dtype=np.int32)#int64\float32
print(a.dtype)  #类型
b = np.zeros((3,5)) #ones empty
print(b)
c = np.arange(0,20,1).reshape((5,4))  #更换juzhenshape  
print(c)
d = np.linspace(1,10,3)  #生成线段 
print(d)

#--------------------------------numpy基础运算--------------------------#
#
e = np.array([10,20,30,40])
f = np.arange(4)
g = e-f  #对位相加减乘除 g = f**2 幂运算
print(e,f,g)
h = 10*np.sin(a)
k = b<3  #判断矩阵

np.sort  #排序

#c =a*b  #对位相乘
#c_dot =np.dot(a,b)  #矩阵相乘
#c_dot_2= a.dot(b)

r = np.random.random((2,4))
print()

np.sum(a)
np.min(a)  #np.min(a,axis =1)  设定不同维度寻找最大值 ,axis = 0在列找最小值 =1在行
np.max(a)

#--------------------------------索引--------------------------#
#索引
A = np.arange(2,14).reshape((3,4))
print(np.argmin(A)) #索引最小值位置 argmax 索引最大值位置
np.mean(A)  #输出平均值  np.mean(A) == A.mean()  ==  np.average(A)
np.median(A)  #输出中位数 均值
np.cumsum(A)   #累加
A[1][2]  #A[1,2]
A[1,:]  #第一行所有  A[:,1]  第一列所有
A[1:3,1:]  #以‘,’为分割,‘:’连接范围
A[::3,:::2]  #第一个‘:’连接范围,说名范围全局,第二个‘:’代表间隔,从第一个起三个一选

for row in A:
    print(row)  #for默认从row行而不是列

for  column in A.T:
    print(column)  #对A进行转置,输出每一列
for item in A.flat:  #迭代器,将A进行平铺 A.flatten()
    print(item)

#--------------------------------合并--------------------------#
A = np.array([1,1,1])  #为序列
B = np.array([2,2,2])
C= np.vstack((A,B)) #上下合并,序列
D = np.hstack((A,B))  #左右合并序列  
E = A[np.newaxis,:]  #对其中的行添加维度
                    #由最初的序列转化为矩阵(1,3),以‘,’为分界线
F = np.concatenate((A,B,A,B),axis =0) #在不同维度进行合并

#--------------------------------分割--------------------------#
A = np.array(12).reshape((3,4))
B = np.split(A,2,axis =1) #将A进行纵向分割,均等分割为两份,,axis = 横向
C = np.vsplit(A,3)  
D = np.hsplit(A,2)

E = np.array_split(A,3,axis =1) #不均等分割

#--------------------------------copy & deep copy--------------------------#
a = np.array(4)
b = a  #赋值 并指向同一地址
b = a.copy()  #  复制,不复制地址

 Pandas

#############################Pandas#################################
#--------------------------------创建列表--------------------------#
import pandas as pd
import numpy as np
s = pd.Series([1,2,3,np.nan,4,1])  #创建列表
dates = pd.date_range('20230910',periods = 6)  #dtype对象类型
df = pd.DataFrame(np.random.randn(6,4),index = dates ,columns = ['a','b','c','d'])
  #生成二维np,六行四列以dates为横坐标,colummns为纵坐标
df1 = pd.DataFrame(np.arange(12).reshape((3,4)))

df2 =pd.DataFrame({'A':1,
                  'B':pd.Timestamp('20130102'),
                  'C':pd.Series(1,index = list(range(4)),dtype ='float32'),
                  'D':np.array([3]*4,dtype = 'int32'),
                  'E':pd.Categorical(['test','train','test','train']),
                  'F':'foo'})
#--------------------------------基础运算--------------------------#
B = df2.dtypes  #指定列对象类型
C = df2.index  #输出列序号
D = df2.columns  #columns
E = df2.values   #输出除了标签以外的values
F = df2.describe()   ##计算数字形式的总数,均值,方差,min等
G = df2.T  #转置
H =df2.sort_index(axis = 1 ,ascending =False)  #排序对axis列进行反向排序
I = df2.sort_values(by = 'E')  #按E进行排序

#--------------------------------选择数据--------------------------#
dates1 = pd.date_range('20230910',periods = 6)  #dtype对象类型
df1 = pd.DataFrame(np.arange(24).reshape((6,4)),index = dates ,columns = ['a','b','c','d'])
#索引
Q1 = df1['a']
Q0 = df1.a
Q2 = df1[:3]
Q3 = df['20230910':'20230912']   #切片

#以标签的形式选择
W1 = df1.loc['20230911']  
W2= df1.loc[:,['a','b']]  #以AB两列进行提取
W3 = df1.loc[:,'a':'c']  #范围切片

#以位置进行索引 numpy  
E1 = df1.iloc[3]  #第三行
E2 = df1.iloc[3,1]   #三行一列
E3  = df1.iloc[3:5,:3] #三行到五行为两列,第零列到第三列有三列
E4 = df1.iloc[[1,3,5],:3]

#Boolean indexing  布尔是否
R = df1[df1.a>5]
R

#--------------------------------选定赋值--------------------------#

df.iloc[2,2] = 111
df.loc['20230910','B'] = 222
df1[df1.a>4] = 0  #将a>4的列变为0
df1.a[df1.a>4] = 0  #只将a>4的这一列换为零
df1['F'] = np.nan   #添加空列
df1['E'] = pd.Series([1,2,3,4,5,6],index =pd.date_range('20230910',periods = 6)  )  #添加列表


#--------------------------------丢失数据处理--------------------------#
df1.iloc[0,1] = np.nan
df1.iloc[1,2] = np.nan
df2 = df1.dropna(axis = 0 ,how = 'any')  #丢弃axis = 0行,其中只要包括nan的行
                                    #how = 'all'  all为所有为nan才丢弃
df3 = df1.fillna(value=5) #将其中nan的数字填上5
a = (np.any(df1.isnull()) == True)  #df.isnull() ==true代表判断是否有缺失,加any整体判断
a
#--------------------------------导入导出数据--------------------------#
#read_csv
#to_csv
data = pd.read_csv('student.csv')
data.pd.to_pickle('student.pickle')  #python自带的压缩文件

#--------------------------------DataFrame合并--------------------------#
import pandas as pd
import numpy as np
df5 = pd.DataFrame(np.ones((3,4))*0,columns = ['a','b','c','d'])
df6 = pd.DataFrame(np.ones((3,4))*1,columns = ['a','b','c','d'])
df7 = pd.DataFrame(np.ones((3,4))*2,columns = ['a','b','c','d'])

#横纵向添加数据,忽略原有index,添加纵向索引  
res = pd.concat([df5,df6,df7],axis = 0,ignore_index = True)  

#join = 'inner'取交集  ,'outer'取并集
df1 = pd.DataFrame(np.ones((3,4))*0,columns = ['a','b','c','d'],index = [1,2,3])
df2 = pd.DataFrame(np.ones((3,4))*1,columns = ['f','k','c','d'],index = [2,3,4])
res1 = pd.concat([df1,df2],join = 'inner',ignore_index = True)  

#左右连接,并通过df1.index的序列进行连接,只有123
res2 = pd.concat([df1, df2.reindex(df1.index)], axis=1)

#append,上下链接将被弃用
res3 = df1.append([df1,df5,df6,df7],ignore_index = True)
res3

数据归一化

"#数据归一化\n",
    "def norm():\n",
    "    #这里是按列统计的\n",
    "    x_col_min = x.min(axis=0)\n",
    "    x_col_max = x.max(axis=0)\n",
    "\n",
    "    #这一步之后,最小值是0\n",
    "    x_norm = x - x_col_min\n",
    "\n",
    "    #这一步之后,最大值是1\n",
    "    x_norm /= x_col_max - x_col_min\n",
    "    return x_norm\n",

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_43952858

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值