jupyter notebook初次以及一些基础练习

一、导入相关库:

import numpy as np
import pandas as pd
from pandas import Series,DataFrame
import matplotlib.pyplot as plt
 
%matplotlib inline

查看版本:

np.__version__
'1.21.5'

1、创建一个长度为10的一维全为0的ndarray对象,然后让第5个元素等于1

s1=np.zeros(shape=10)
s1
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

2、创建一个元素为从10到49的ndarray对象

np.random.randint(10,50,size=10)
array([17, 47, 48, 15, 31, 29, 40, 37, 48, 29])

3、将第2题的所有元素位置反转

np.linspace(10,49,10,)
array([10.        , 14.33333333, 18.66666667, 23.        , 27.33333333,
       31.66666667, 36.        , 40.33333333, 44.66666667, 49.        ])

4、使用np.random.random创建一个10*10的ndarray对象,并打印出最大最小元素

a=np.arange(10,30)
a
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
       27, 28, 29])

5、创建一个10*10的ndarray对象,且矩阵边界全为1,里面全为0

a[::-1]
array([29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13,
       12, 11, 10])
a4=np.random.random(size=(10,10))
a4
array([[0.06807205, 0.03502089, 0.14992074, 0.30566893, 0.12048629,
        0.95628898, 0.26167095, 0.90374573, 0.03062862, 0.65527569],
       [0.97361905, 0.76021575, 0.88422956, 0.78572215, 0.04781774,
        0.44859979, 0.68168909, 0.42140251, 0.03958027, 0.37815643],
       [0.7606728 , 0.6263286 , 0.17997144, 0.7036724 , 0.55832459,
        0.6373475 , 0.17774823, 0.61617329, 0.89717451, 0.30591182],
       [0.70275554, 0.82429948, 0.4809848 , 0.23453189, 0.49858396,
        0.65011633, 0.90957194, 0.77746555, 0.36504953, 0.60885652],
       [0.15417352, 0.85885888, 0.12505416, 0.08618482, 0.89871086,
        0.98628663, 0.10181007, 0.74022539, 0.43006737, 0.27784418],
       [0.02176644, 0.82156081, 0.35552007, 0.85644022, 0.0499188 ,
        0.77794809, 0.1312208 , 0.50151863, 0.78710983, 0.27712318],
       [0.56037693, 0.8164706 , 0.65199186, 0.06502219, 0.70029236,
        0.57050617, 0.23690135, 0.99429557, 0.06027634, 0.46245927],
       [0.54157995, 0.70066127, 0.4082769 , 0.54263473, 0.41281777,
        0.04117956, 0.84954684, 0.78505542, 0.61213947, 0.06043471],
       [0.59244853, 0.46910702, 0.24054715, 0.20004793, 0.7516975 ,
        0.86454468, 0.93419921, 0.5150131 , 0.06015795, 0.42691981],
       [0.88373947, 0.36547369, 0.3361059 , 0.36825001, 0.67635111,
        0.66065482, 0.05312939, 0.86928988, 0.54312531, 0.77506493]])
zmin,zmax=a4.min(),a4.max()
zmin,zmax
(0.021766439574886776, 0.9942955734485718)
nd=np.zeros(shape=(10,10),dtype=np.int8)
nd[[0,9]]=1
nd[:,[0,9]]=1
nd
array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], dtype=int8)
a5=np.ones(shape=(10,10),dtype=np.int8)
a5[1:-1,1:-1]=0
a5
array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], dtype=int8)

6、创建一个每一行都是从0到4的5*5矩阵

l=[0,1,2,3,4]
nd=np.array(l*5)
nd.reshape(5,5)
array([[0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4]])
nd_6=np.arange(0,25).reshape(5,5)
nd_6
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])
nd6=np.arange(0,5,1)
nd6
array([0, 1, 2, 3, 4])
nd_6[0:5]=nd6
nd_6
array([[0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4]])

7、创建一个范围在(0,1)之间的长度为12的等差数列

np.linspace(0,1,12)
array([0.        , 0.09090909, 0.18181818, 0.27272727, 0.36363636,
       0.45454545, 0.54545455, 0.63636364, 0.72727273, 0.81818182,
       0.90909091, 1.        ])

8、创建一个长度为10的随机数组并排序

a=np.random.random(10)
a
array([0.33357218, 0.7477204 , 0.39546299, 0.2120832 , 0.5572556 ,
       0.86805748, 0.42911611, 0.35832651, 0.54973435, 0.25861297])
np.sort(a)
array([0.2120832 , 0.25861297, 0.33357218, 0.35832651, 0.39546299,
       0.42911611, 0.54973435, 0.5572556 , 0.7477204 , 0.86805748])
a.argsort()
array([3, 9, 0, 7, 2, 6, 8, 4, 1, 5], dtype=int64)
a[a.argsort()]
array([0.2120832 , 0.25861297, 0.33357218, 0.35832651, 0.39546299,
       0.42911611, 0.54973435, 0.5572556 , 0.7477204 , 0.86805748])

9、创建一个长度为10的随机数组并将最大值替换为0

nd=np.random.randint(0,10,size=10)
display(nd)
index_max=nd.argmax()
array([0, 4, 9, 9, 2, 3, 4, 9, 7, 3])
nd[index_max]
9
all_index_max=np.argwhere(nd==nd[index_max]).reshape(-1)
all_index_max
array([2, 3, 7], dtype=int64)
ddnd
array([0, 0, 6, 0, 5, 3, 7, 7, 0, 0])
nd[all_index_max]=0
nd
array([0, 4, 0, 0, 2, 3, 4, 0, 7, 3])

10、如何根据第3列来对一个5*5矩阵排序?

n10=np.random.randint(0,100,size=(5,5))
n10
array([[16, 90, 95, 41, 88],
       [15, 54, 92, 66, 31],
       [ 0, 91, 31,  0, 31],
       [27, 76, 39, 54, 97],
       [60, 93, 67, 89, 52]])
n10[:,2]
array([95, 92, 31, 39, 67])
np.argsort(n10[:,2])
array([2, 3, 4, 1, 0], dtype=int64)
n10[np.argsort(n10[:,2])]
array([[ 0, 91, 31,  0, 31],
       [27, 76, 39, 54, 97],
       [60, 93, 67, 89, 52],
       [15, 54, 92, 66, 31],
       [16, 90, 95, 41, 88]])

Pandas

Series数据结构

import pandas as pd
import numpy as np

s1 = pd.Series([1,2,3,4,5])
print(s1)
s2 = pd.Series({"a": 1, "b": 2})  # 字典创建Series,索引值为字典的key值
print(s2['a'])
s3 = pd.Series(data=[1,2,3,4,5], index=np.arange(0,1,0.2))  # 索引值不一定是整数,还可以是其他的一些类型
print(s3[0.2])

0    1
1    2
2    3
3    4
4    5
dtype: int64
1
2

增加数据成员

import pandas as pd


arr = pd.Series(range(0, 5, 1))
print(arr)
arr = pd.concat([arr,arr],ignore_index=True)
print(arr)

0    0
1    1
2    2
3    3
4    4
dtype: int64
0    0
1    1
2    2
3    3
4    4
5    0
6    1
7    2
8    3
9    4
dtype: int64

删除数据成员:

import pandas as pd


arr = pd.Series(range(0, 5, 1), range(1, 6, 1))
print(arr)
arr = arr.drop(2)  ## 根据索引进行删除
print(arr)
1    0
2    1
3    2
4    3
5    4
dtype: int64
1    0
3    2
4    3
5    4
dtype: int64

DataFrame对象

import pandas as pd


dict = {'col1': [1,2,None], 'col2': ['a','b', None]}  # 注意:All arrays must be of the same length,也就是说数组的长度应该要相同,不相同的话可以使用None进行占位
df = pd.DataFrame(dict)
print(df)
   col1  col2
0   1.0     a
1   2.0     b
2   NaN  None
import pandas as pd


list1 = [1,2,3]
list2 = [2,3,4]
df = pd.DataFrame({'col1': list1, 'col2': list2})
print(df)
   col1  col2
0     1     2
1     2     3
2     3     4
import numpy as np 
import pandas as pd


pd = pd.DataFrame(np.arange(0,20,1).reshape(4,5), index=['a','b','c','d'], columns=['1','2','3','4','5'])
print(pd)
print()
print(pd['1'])
print()
print(pd['1']['a'])
    1   2   3   4   5
a   0   1   2   3   4
b   5   6   7   8   9
c  10  11  12  13  14
d  15  16  17  18  19

a     0
b     5
c    10
d    15
Name: 1, dtype: int32

0

切片:

import numpy as np 
import pandas as pd


fd = pd.DataFrame(np.arange(0,20,1).reshape(4,5), index=['a','b','c','d'], columns=['1','2','3','4','5'])
print(fd.loc[['a', 'b'], ['1', '3']])
print()
print(fd.iloc[0:1, 2:3])
   1  3
a  0  2
b  5  7

   3
a  2

添加数据:

import numpy as np
import pandas as pd


fd = pd.DataFrame(np.arange(0,20,1).reshape(4,5), index=['a','b','c','d'], columns=['1','2','3','4','5'])
fd['f']=9  # 增加列,
print(fd)
    1   2   3   4   5  f
a   0   1   2   3   4  9
b   5   6   7   8   9  9
c  10  11  12  13  14  9
d  15  16  17  18  19  9

删除数据:

import numpy as np
import pandas as pd


fd = pd.DataFrame(np.arange(0,20,1).reshape(4,5), index=['a','b','c','d'], columns=['1','2','3','4','5'])
print(fd)
print(fd.drop(columns='1'))  # 删除‘1’列, column代表待删除的列名
print(fd.drop(index='a'))  # 删除‘a’行,index代表待删除的行名
fd.drop(index='a', axis=1, inplace=True)  # 从原数据中删除数据,axis表示是删除一行还是删除一列
print(fd)
    1   2   3   4   5
a   0   1   2   3   4
b   5   6   7   8   9
c  10  11  12  13  14
d  15  16  17  18  19
    2   3   4   5
a   1   2   3   4
b   6   7   8   9
c  11  12  13  14
d  16  17  18  19
    1   2   3   4   5
b   5   6   7   8   9
c  10  11  12  13  14
d  15  16  17  18  19
    1   2   3   4   5
b   5   6   7   8   9
c  10  11  12  13  14
d  15  16  17  18  19

数据对齐

import pandas as pd 

s1 = pd.Series({'color':1, 'size':2, 'weight':3})
s2 = pd.Series({'color':5, 'size':7, 'weight':4.5, 'priec': 1})
print(s1 * s2)
color      5.0
priec      NaN
size      14.0
weight    13.5
dtype: float64
import pandas as pd 

s1 = pd.Series({'color':1, 'size':2, 'weight':3})
s2 = pd.Series({'color':5, 'size':7, 'weight':4.5, 'priec': 1})
print(s1.add(s2, fill_value=0))  # 其他的函数也是同理
color     6.0
priec     1.0
size      9.0
weight    7.5
dtype: float64

缺失数据的处理:dropna()

import pandas as pd


data = pd.Series([1,2,None,4])
print(data.dropna(axis=0))  # 这里的axis是判断对行还是列进行过滤,这里是过滤列,如果想过滤行就将axis=1

dfHow = pd.DataFrame([[1,2,None], [None, None, None], [1,1,1]])
print(dfHow.dropna(axis=0, how='any'))  # how参数:any只要有None值就删除,all必须要一整行或者整列是None才删除
print()
print(dfHow.dropna(axis=0, how='all'))
import pandas as pd


data = pd.Series([1,2,None,4])
print(data.dropna(axis=0))  # 这里的axis是判断对行还是列进行过滤,这里是过滤列,如果想过滤行就将axis=1

dfHow = pd.DataFrame([[1,2,None], [None, None, None], [1,1,1]])
print(dfHow.dropna(axis=0, how='any'))  # how参数:any只要有None值就删除,all必须要一整行或者整列是None才删除
print()
print(dfHow.dropna(axis=0, how='all'))
0    1.0
1    2.0
3    4.0
dtype: float64
     0    1    2
2  1.0  1.0  1.0

     0    1    2
0  1.0  2.0  NaN
2  1.0  1.0  1.0
0    1.0
1    2.0
3    4.0
dtype: float64
     0    1    2
2  1.0  1.0  1.0

     0    1    2
0  1.0  2.0  NaN
2  1.0  1.0  1.0

Matplotlib

import matplotlib.pyplot as plt


fig = plt.figure()
# 创建三个子图
# ax1=fig.add_subplot(2,2,1)
# ax2=fig.add_subplot(2,2,2)
# ax3=fig.add_subplot(2,2,3)

# 创建6个子图
fig,axes=fig.subplots(2,3)

在这里插入图片描述

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
rect = plt.Rectangle((0.2,0.75), 0.4, 0.15, color='r',alpha=0.3)  # 创建一个长方形对象
ax.add_patch(rect)  # 将图形添加到画布中,同理,其他的图形也是这样操作的,只是一些参数不同而已
<matplotlib.patches.Rectangle at 0x188f488cc10>

在这里插入图片描述

plot函数

需要绘制曲线时就是使用到plot函数,绘制需要在画布上进行,如果没有创建画布的话,那么会先隐式的创建一个画布
plot(x, y, format_string, ** kwargs)
参数:
x: x轴数据,列表或者数组,可选
y: y轴数据,列表或数组。
format_string:控制曲线的格式字符串,可选
** kwars:第二组或者更多组参数(x, y, format_string)

import matplotlib.pyplot as plt
import numpy as np

a = np.arange(0,10,1)
plt.xlabel('x')
plt.ylabel('y')
plt.plot(a, a * 1.5, a, a * 2, a, a * a)  # 里面的参数一共分为三组,((a, a * 1.5), (a, a * 2), (a, a * a))
plt.legend(['1.5x', '2.0x', 'x*x'])
plt.show()

在这里插入图片描述

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-10, 10, 100)
y = np.sin(x)
plt.plot(x, y, marker='o')
plt.show()

在这里插入图片描述

绘制3D图

mpl_toolkits.mplot3d包提供了一些基本的3D绘图功能,其支持的图标类型包括散点图、曲面图、线图和网格图。坐标轴是Axes3D,绘制时腰围三个坐标轴提供数据。

函数mpl_Axes3D.plot()可以绘制三维曲线图,其基本格式如下:
plot(xs, ys, * zs, * zdir, * args, ** kwargs)
参数说明:xs,ys,* zs: 分别代表x,y,z坐标轴,如果没有zs参数则绘制2D图。
zdir: 使用哪个方向作为z(取值’x’,‘y’,‘z’)
————————————————

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def randrange(n, randFloor, randCeil):
    rnd = np.random.rand(n)  # 生成n个随机数
    return (randCeil - randFloor) * rnd + randFloor

plt.rcParams['font.sans-serif']=['SimHei']  # 设置中文
fig = plt.figure(figsize=(10, 8)) 
ax = fig.add_subplot(111, projection='3d')  # 添加子3D坐标轴
n = 100
for zmin, zmax, c, m, l in [(4,15,'r','o', '低值'), (13,40,'g','*', '高值')]:
    x = randrange(n, 0, 20)
    y = randrange(n, 0, 20)
    z = randrange(n, zmin, zmax)
    ax.scatter(x, y, z, c=c, marker=m, label=l, s=z*6)

ax.set_xlabel('X-value')
ax.set_ylabel('Y-value')
ax.set_zlabel('Z-value')

ax.set_title('高/低值3D散点图', alpha=0.6, size=15, weight='bold')
plt.show()

在这里插入图片描述

总结:题目练习算是重新开始学习一遍有关numpy等的一些知识,然而在安装anaconda时,跟着步骤盲目实行更新pip时,由于该pip所在文件夹user的权限不够,使得该步骤出错,只卸载了旧版 ,未安装新版,所以要更新的话需要找到文件夹修改相关属性或是在那个命令后加–user。

什么是图灵测试

图灵测试(TheTuringtest)由艾伦·麦席森·图灵发明,指测试者与被测试者(一个人和一台机器)隔开的情况下,通过一些装置(如键盘)向被测试者随意提问。进行多次测试后,如果有超过百分之30的测试者不能确定出被测试者是人还是机器,那么这台机器就通过了测试,并被认为具有人类智能。

参考链接:

https://blog.csdn.net/molongqishi/article/details/129390738?spm=1001.2014.3001.5502

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值