python学习 | python基础习题

1、打印一个函数的帮助文档,比如 numpy.add

import numpy as np
print(help(np.info(np.add)))

2、 创建一个取值在 10-100 之间的数据构成的数组(数组长度可以自己义), 并将其倒序排列,然后打印出来。

import numpy as np

a=np.arange(10,100,5)
print(a)

a=a[::-1 ]#这个操作是逆序操作
print(a)

答案:

[10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95]

[95 90 85 80 75 70 65 60 55 50 45 40 35 30 25 20 15 10]

3、 创建一个数组,然后找到这个数组中不为 0 的数据的索引。

import numpy as np

a = np.arange(12).reshape(3, 4)
print(a)

print(np.nonzero(a))
#np.nonzero(a)输出的是两个array第一个array中的值指的是行,第二个指的是列

答案:

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
 
(array([0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2], dtype=int64), array([1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3], dtype=int64))

4、 随机构造一个 5*5 矩阵,并打印其中最大与最小值。

import numpy as np

a=np.random.random((5,5))
print(a)

print(a.min())

print(a.max())

答案:

[[0.05287482 0.74427572 0.73539342 0.83938146 0.39445586]
 [0.79483501 0.46700273 0.01471763 0.00595255 0.51912868]
 [0.72950056 0.70111085 0.85719474 0.28030179 0.85527987]
 [0.46919346 0.39718407 0.79402426 0.35401079 0.06972197]
 [0.23025856 0.74368634 0.9521544  0.76051915 0.97153536]]
 
0.005952550919826938
0.9715353569216929

5、 构造一个 5*5 的矩阵,令其值都为 1,并在最外层加上一圈 0,将结果打印 出来。

import numpy as np

cui_array=np.ones((5,5))

cui_array2=np.pad(cui_array,pad_width=1,mode='constant',constant_values=0)

print(cui_array2)

答案:

[[0. 0. 0. 0. 0. 0. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 0. 0. 0. 0. 0. 0.]]

6、 构造一个 5*5 的矩阵,其元素为不超过 25 的整数,交换矩阵中的前两行。

import numpy as np

z=np.arange(25).reshape(5,5)

print(z)

z[[0,1]]=z[[1,0]] #交换矩阵当中的一二两行

print(z)

答案:

[[ 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]]
 
[[ 5  6  7  8  9]
 [ 0  1  2  3  4]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]

7、 构造一个 50 个元素的数组,其取值由从 0 到 10 范围的整数随机组成,找到 该数组中最常出现的数字。

import numpy as np

z=np.random.randint(0,10,50)

print(z)
print("最常出现得数字是:")
print(np.bincount(z).argmax())

答案:

[0 0 9 5 1 5 5 5 4 6 9 9 9 9 6 2 4 1 1 5 8 8 3 9 9 7 0 7 3 9 3 2 7 2 1 1 9 8 1 6 8 6 1 8 8 1 1 8 9 0]
 
最常出现得数字是:
9

8、 使用 pandas 的 Data Frame 创建一个表格,并将表格打印出来。

import pandas as pd
import numpy as np

data = { 'animal':['cat','cat','snake','dog','dog','cat','snake','cat','dog','dog'],
'age': [2.5, 3.0, 0.5, None, 5.0,2.0,4.5,None,7.0,3.0],
'visits': [1, 3, 2, 3, 2,3,1,1,2,1],
'priority': ['yes', 'yes', 'no', 'yes', 'no','no','no','yes','no','no']}

a=pd.DataFrame(data,index=['a','b','c','d','e','f','g','h','i','j'])
print(a)

答案:

  animal  age  visits priority
a    cat  2.5       1      yes
b    cat  3.0       3      yes
c  snake  0.5       2       no
d    dog  NaN       3      yes
e    dog  5.0       2       no
f    cat  2.0       3       no
g  snake  4.5       1       no
h    cat  NaN       1      yes
i    dog  7.0       2       no
j    dog  3.0       1       no

9、 打印上面表格的前三行数据。

a.head(3) 

答案:

在这里插入图片描述


10、查找 animal 为“cat”并且 age 取值小于 3 的数据行,并打印出来。

a[(a['animal']== 'cat')&(a['age'] <3)]

答案:
在这里插入图片描述


11、将 f 行中的 age 值修改为 1.5,并将其打印出来。

a.loc['f','age'] = 1.5
print(a)

答案:

  animal  age  visits priority
a    cat  2.5       1      yes
b    cat  3.0       3      yes
c  snake  0.5       2       no
d    dog  NaN       3      yes
e    dog  5.0       2       no
f    cat  1.5       3       no
g  snake  4.5       1       no
h    cat  NaN       1      yes
i    dog  7.0       2       no
j    dog  3.0       1       no

12、计算每一种动物的平均年龄,并将结果打印出来。

cat=a[(a['animal']== 'cat')]
#print(cat)
print("cat平均年龄")
cat[['age']].mean(axis=0)
# axis = 0表示对纵向求平均值,axis = 1表示对横向求平均值

snake=a[(a['animal']== 'snake')]
#print(snake)
print("snake平均年龄")
snake[['age']].mean(axis=0)

dog=a[(a['animal']== 'dog')]
#print(dog)
print("dog平均年龄") 
dog[['age']].mean(axis=0)

答案:

cat平均年龄
age    2.333333
dtype: float64

snake平均年龄
age    2.5
dtype: float64

dog平均年龄
age    5.0
dtype: float64

13、计算每一种动物的数量,并将结果打印出来。

cat=a[(a['animal']== 'cat')]
print("cat的数量")
cat[['animal']].count(axis=0)

snake=a[(a['animal']== 'snake')]
print("snake的数量")
snake[['animal']].count(axis=0)

dog=a[(a['animal']== 'dog')]
print("dog的数量")
dog[['animal']].count(axis=0)

答案:

cat的数量
animal    4
dtype: int64

snake的数量
animal    2
dtype: int64

dog的数量
animal    4
dtype: int64

14、将所有 animal 中的”cat”修改为“bear”,并将结果打印出来。

a=a.replace('cat','bear' )
print(a)

答案:

  animal  age  visits priority
a   bear  2.5       1      yes
b   bear  3.0       3      yes
c  snake  0.5       2       no
d    dog  NaN       3      yes
e    dog  5.0       2       no
f   bear  1.5       3       no
g  snake  4.5       1       no
h   bear  NaN       1      yes
i    dog  7.0       2       no
j    dog  3.0       1       no

15、针对每一种 animal,计算其不同的 visits 取值情况下的平均年龄,并将结 果打印出来(提示:可以采用数据透视表 pivot_table)。

pd.pivot_table(a,index=["animal"],values=["age"],columns=["visits"])

答案:
在这里插入图片描述


16、首先构造出下图的数据表格,然后,使用线性插值的方法,将 FlightNumber 中的空值补上值,并打印出来结果。

 data2 = { 'From_To':['LoNDon_paris','MAdrid_miLAN','londON_Stockholm','Budapest_PaRis','Brussels_londOn',] ,
           'FlightNumber': [10045.0,None,10055.0,None,10085.0] ,
           'RecentDelays': [[23,47],[],[24,43,87],[13],[67,32]] ,
           'Airline': ['KLM(!)', '<Air France>(12)', '(British Airways.)', '12.Air France','"Swiss Air"']
           }

b=pd.DataFrame(data2)
print(b)

b.fillna(0)

答案:

            From_To  FlightNumber  RecentDelays             Airline
0      LoNDon_paris       10045.0      [23, 47]              KLM(!)
1      MAdrid_miLAN           NaN            []    <Air France>(12)
2  londON_Stockholm       10055.0  [24, 43, 87]  (British Airways.)
3    Budapest_PaRis           NaN          [13]       12.Air France
4   Brussels_londOn       10085.0      [67, 32]         "Swiss Air"

在这里插入图片描述


17、编写程序 ,网址中下载数据,将数据存储到一个 DataFrame 中,然后打印这个 DataFrame 的内容。

import os
import requests
import csv

url='https://archive.ics.uci.edu/ml/machine-learning-databases/00383/risk_factors_cervical_cancer.csv'

response = requests.get(url)

with open(os.path.join("data", "file"), 'wb') as f:
    f.write(response.content)
    
tmp_lst = []

with open(os.path.join("data", "file"), 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        tmp_lst.append(row)
        
df = pd.DataFrame(tmp_lst[1:], columns=tmp_lst[0]) 
print(df)

18、绘制数据图:每个点的横坐标为从 0 到 10 之间相隔 0.5 的数,每个点的纵坐标也为从 0 到 10 之间相隔 0.5 的数,曲线为红色虚线;每个点的横坐标为从 0 到 10 之间相隔 0.5 的数,每个点的纵坐标为从 0 到 10 之间相隔 0.5的数的平方,曲线为蓝色正方形点虚线;每个点的横坐标为从 0 到 10 之间相隔 0.5 的数,每个点的纵坐标也为从 0 到 10 之间相隔 0.5 的数的立方,曲线 为绿色圆点虚线。

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0,100,1)
y=np.random.randint(0,13,100)
z=np.random.randint(15,40,100)

plt.plot(x,y,'bs-')
plt.plot(x,z,color='red',linestyle='--')


x = np.arange(0,100,10)
y = []

plt.plot(x,x,color='red',linestyle='--')
plt.plot(x,x*x,'bs')
plt.plot(x,x*x*x,'go')

答案:
在这里插入图片描述
在这里插入图片描述


19、绘制一个两行一列的图,其中第一个图为余弦曲线图,横坐标范围为[-10,10],线条颜色为蓝色;第二个图为正弦曲线图,横坐标范围为[-10,10], 线条颜色为红色。

import matplotlib.pyplot as plt
import numpy as np
import math

x = np.linspace(-10, 10, 1000)

y1 = np.cos(x)
y2 = np.sin(x)

plt.figure()

ax1 = plt.subplot(2,1,1)
ax2 = plt.subplot(2,1,2)

plt.sca(ax1)
plt.plot(x,y1,'b-')
plt.yticks([-1,-0.5,0,0.5,1],rotation=0)

plt.sca(ax2)
plt.plot(x,y2,'r-')
plt.yticks([-1,-0.5,0,0.5,1],rotation=0)

plt.show()

答案:
在这里插入图片描述


20、绘制子图布局

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

plt.figure()
gs=gridspec.GridSpec(3,3) #通过gridspec.GridSpec()创建区域

ax1=plt.subplot(gs[0,:1])
ax2=plt.subplot(gs[1,:1])
ax3=plt.subplot(gs[2,:2])#第三行,第一列,占2列
ax4=plt.subplot(gs[0:2,1])#第一行,第二列,占2行
ax5=plt.subplot(gs[0:3,2])#第一行,第三列,占3行

plt.show()

答案:
在这里插入图片描述


21、绘制下面的立体图(提示:使用 mpl_toolkits.mplot3d 中的 Axes3D):其中 x 坐标取值范围为[-4,4],每隔 0.25 取一个值;y 坐标取值范 围为[-4,4],每隔 0.25 取一个值;z 坐标取值为 x2+y2 的平方根。

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
 
 
fig = plt.figure()
ax = fig.gca(projection='3d')
 
# Make data.
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
 
# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.hsv,
                       linewidth=0, antialiased=False)
 
# Customize the z axis.
ax.set_zlim(-1, 1)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
 
# Add a color bar which maps values to colors.
#fig.colorbar(surf, shrink=0.5, aspect=5)
 
plt.show()

答案:
在这里插入图片描述


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值