内农大数据可视化

#从键盘输入两个字符,并输出。
a = str(input('输出字符串1'))
print(a)

#请输入某位同学的三门成绩(语文、英语、数学),计算总分和平均分并输出。
a = int(input())
b = int(input())
c = int(input())
d = a+b+c
e = (a+b+c)/3
print(f'{d:.2f}')
print(f'{e:.2f}')

#请输入球的半径,输出球的直径,表面积和体积
import math
k = math.pi
r = eval(input())
D = 2*r
S = 4*k*r*r
V = 4/3*k*r*r*r
print(D,S,V)

#用户在三行中分别输入一个字符串s和两个整数m、n,输出字符串s中位于m和n(包括m但不包括n)之间的子字符串
s = input()
m = int(input())
n = int(input())
print(s[m:n])

#用户输入一个字符串,将其中小写字母全部转换成大写字母,把大写字母全部转换为小写字母,其他字符不变
s = str(input("a"))
print(s.swapcase())

#输入一个三位数字,输出每位上数字的立方和。
n = int(input())
x = int(n/100)
y = int(n/10%10)
z = int(n%10)
m = x**3+y**3+z**3
print(m,x,y,z)

#闰年
year = int(input())
if year%100==0:
    if year%400 ==0:
        print("366")
    else:
        print("365")
else:
    if year%4 == 0:
        print(366)
    else:
        print(365)

#水仙花数
n = int(input())
x = int(n/100)
y = int(n/10%10)
z = int(n%10)
m = x**3+y**3+z**3
if m==n:
    print(n,"yes")

#100-1000之间的水仙花数
for a in range(100,1000):
    x = int(a/100)
    y = int(a/10%10)
    z = int(a%10)
    m = x**3+y**3+z**3
    if m ==a:
        print(a)

#用户登录
user = ['root','admin']
password = ['123','123']
count = 0
while count<3:
    Name = input()
    password1 = input()
    count +=1
    if Name in user:
        if password1 == password[user.index(Name)]:
            print(Name)
            break
        else:
            print(Name)
            print((3-count))
    else:
        print('%s aha'%(Name))
        print((3-count))
else:
    print("clear")


'''生成一个包含数字1,2,3,...,99的列表,
输出列表的值;输入一个2~9之间的正整数,
查找列表中是否存在有这个数的倍数和数位上包含这个数字的数,
若存在,将其从列表中删除,输出删除后的列表。(
例如,输入"7",删除列表中7的倍数和数位上包含7的数,
再输出列表
'''
a = range(1,100)
la = list(a)
number = int(input())
for x in range(1,100):
    if x % number ==0 or x % 10 ==number or x//10==number:
        la.remove(x)
print(la)

#用户登录
'''userDict = {'admin':'123456','
administrator':'12345678','root':'password'},
其键和值分别代表用户名与密码,请编程实现用户登录验证。
用户输入用户名和密码,
当用户名与密码和字典中中的某个键值对匹配时,
显示”登录成功“,否则显示”登录失败“,
登陆失败时允许重复输入三次
'''
userDict = {
    'admin':'123456',
    'administrator':'12345678',
    'root':'password'
}
count = 0
while count<3:
    Name = input()
    password1 = input()
    count +=1
    if Name in userDict.keys():
        if userDict[Name] == password1:
            print(Name)
            break
        else:
            print(Name)
            print((3-count))
    else:
        print('%s aha'%(Name))
        print((3-count))
else:
    print("clear")

'''
删除第2题用户密码字典中用户名为"admin"的元素,
更新root用户的密码为"root123",
增加一个用户"super",密码设为"super999"
'''
str(userDict)
userDict['root'] = "root123"
userDict['super'] = "super999"
str(userDict)

T = ('python','java','web编程','机器学习','图像处理','数据结构','java','人工智能')
T = T + ('操作系统',)
#向元组添加元素‘操作系统’,是否成功
[print(c) for c in T]
#分别用 for 、 while 语句,遍历输出元组元素
print(T.count('java'))
#统计‘java’在元组中出现的次数
print(T.index('数据结构'))
#查找‘数据结构’在元组中的位置
L = list(T)
#把元组转换成列表 L1
s = str(T)
#把元组转换成字符串 S
print(T)
print(L)
print(s)

T2 = ('大数据','计科','软工','网工')
T3 = T+T2
T3
#有元组 T2=(‘ 大数据 ’,’ 计科 ’,’ 软工 ’,’网工‘) ,
#连接元组 T1和 T2 生成新元组 T3

#查找文件默认存储路径
import os
print(os.path.abspath('.'))

print('''
1.欢迎进入身份认证系统
2.登录
3.退出
4.认证
''')

#去重进行从小到大排序输出
s = "asdfg"
print(sorted(list(set(s))))

#提取奇数构造新列表
a =[1,2,3,4,5,6]
print([i for i in a if i% 2 ==1])

#将两个列表进行合并
a = [1,5,7,9]
b = [2,2,6,8]
c = []
c.extend(a)
c.extend(b)
c

#使用pop和del删除字典
dic = {"name":"zs",
        "age":18
      }
dic.pop("name")
dic

del dic['age']
dic

#实现字符串的替换
string = 'life is short'
print(string.replace("short","long"))

#bmi
h = float(input())
w = float(input())

def Bmi(w,h):
    bmi = w/(h*h)
    if bmi< 18.5:
        return "过轻"
    else:
        return"aaa"
print(Bmi(w,h))

#输出1-10之间的素数
import math
def number(n):
    if n==0 or n ==1:
        return False
    for i in range(2,int(math.sqrt(n))+1):
        if n % i ==0:
            return False
        return True
ans = [i for i in range(10) if number(i)]
ans

#自定义函数完成交换两个数值
def swap(a,b):
    return b,a
a = 1
b = -1
print(swap(a,b))

#1到n求和
def sum(n):
    sum=0
    for i in range(1,n+1):
        sum+=i
    return sum
print(sum(100))

'''
已知列表[1,2,3,4,5],
请使用map()函数输出[3,6,9,12,15],
并使用列表推导式提取出大于8的数,
最终输出[9,12,15]
'''
a = [1,2,3,4,5]
b = list(map(lambda x:x*3,a))
print(b)
print([i for i in b if i >8])

#用lambda函数实现两个数相加
sum = lambda a,b:a+b
print(sum(1,2))

#使用filter函数求出列表所有偶数并构造新列表,a=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = [1,2,3,4,5,6,7,8,9,10]
list(filter(lambda x:x%2 ==0,a))

#调用 numpy 的 array 函数创建一维数组a1,
#一维数组a2(指定dtype为float)
#二维数组a3以及三维数组a4,如下图所示
import numpy as np
a1 = np.array([0,1,2,3,4,5,6,7])
a2 = np.array([0,1,2,3,4,5,6,7],dtype=float)
a3 = np.array([[0,1,2,3],[4,5,6,7]])
a4 = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
a1
a2
a3
a4

'''
定义一个结构化数据类型 xs_struc,
包含字符串字段 id、name,
整数字段 age及浮点字段 grade,
并将这个 dtype 应用到 ndarray对象xs_rec
'''
import numpy as np
xs_struc = np.dtype([('id','<u4'), ('name', '<U10'), ('age', 'i1'),('grade','<f4')]) 
a = np.array([('1001', 'zhangsan', 20,90),('1002','lisi' ,21, 88),('1000','wangwu',20,91)], dtype =xs_struc ) 
print(xs_struc)
print(a)

'''
使用np.arange()函数快速创建以下两个数组:
第1个是含0-9数值的数组,
第2个是从2开始,100以内,
等差值为10的数组,如下图所示:'''
import numpy as np
a1 = np.arange(10)
a2 = np.arange(2,101,10)
print(a1)
print(a2)

#创建形状为(3,4),dtype=int的全0数组,如下图所示
import numpy as np
np.zeros((3,4),dtype=int)

#使用ndim查看各数组的维度,输出结果分别为1 2 3。
import numpy as np
a1 = np.array([0,1,2,3,4,5,6,7])
a2 = np.array([0,1,2,3,4,5,6,7],dtype=float)
a3 = np.array([[0,1,2,3],[4,5,6,7]])
a4 = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
print(a1.ndim)
print(a3.ndim)
print(a4.ndim)

'''
分别使用reshape()方法和
resize()函数将a3转化为形状为(4,2)的数组b31和b32,
输出结果如下图所示:'''
import numpy as np
a3 = np.array([[0,1,2,3],[4,5,6,7]])
b = a1.reshape(4,2) 
print(b)
c =np.resize(a3,(4,2))
print(c)

#分别使用ravel()函数、flatten()和reshape()方法将数组a4展平
import numpy as np
a4 = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
print(a4.flatten())
print(a4.reshape(1,8))
print(a4.flatten())


#① 使用整数索引,获取数组a3中如图所示的元素,输出结果为[6]。
#② 使用整数数组索引,获取数组a4中如图所示的元素,输出结果为[2 1]。
#③ 使用布尔索引,获取数组a4中大于5的元素,输出结果为[6 7]。
#④ 使用字段名索引,获取数组xs_rec中lisi的学号、年龄和分数,输出结果为1002 21 88.0。
import numpy as np
a1 = np.array([0,1,2,3,4,5,6,7])
a2 = np.array([0,1,2,3,4,5,6,7],dtype=float)
a3 = np.array([[0,1,2,3],[4,5,6,7]])
a4 = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
xs_struc = np.dtype([('id','<u4'), ('name', '<U10'), ('age', 'i1'),('grade','<f4')]) 
a = np.array([('1001', 'zhangsan', 20,90),('1002','lisi' ,21, 88),('1000','wangwu',20,91)], dtype =xs_struc ) 
print(a3[[1],[2]])
print(a4[[0],[1,0],[0,1]])
print(a4[a4>5])

print(a['name'])
print(a[1])
print(a[1]['id'])
print(a[1]['age'])
print(a[1]['grade'])

#创建一个2维10*10数组,使该数组边界值为1,内部的值为0
a=np.arange(100).reshape(10,10)
a[:,:]=1
a[1:9]=0
a[...,(0,9)]=1
a

'''
对以下语句生成的数组a5分别按行和列排序,
输出结果如下图所示:
a5=np.array([2,13,72,44,62,3,6,456,24,7,85,93,89,5]).reshape(7,2)
'''
a5=np.array([2,13,72,44,62,3,6,456,24,7,85,93,89,5]).reshape(7,2)
a5.sort(axis=0)
a5
#按列

a5=np.array([2,13,72,44,62,3,6,456,24,7,85,93,89,5]).reshape(7,2)
a5.sort(axis=1)
a5
#按行

#对以下语句生成的两个二维数组按要求进行组合与分拆
a1 = np.arange(6).reshape((3, 2))
a2 = np.array([[0, 1], [1, 0], [2, 1]])
b=np.hstack((a1,a2))#水平方向
c=np.vstack((a1,a2))#竖直方向
print(b,c)

#对arr1和arr2在0轴和1轴上分别完成拼接,输出结果如下图所示
d=np.concatenate((a1,a2),axis = 0)#竖直方向
e =np.concatenate((a1,a2),axis = 1)#水平方向
print(d,e)

#对a1完成水平分拆和垂直分拆
np.hsplit(a1,2) #竖直

np.vsplit(a1,3)

#对arr1在0轴和1轴上分别完成分拆,输出结果如下图所示
np.split(a1,2,axis=1)

np.split(a1,3,axis=0)

#pandas 根据列表[2, 8, -5, 6, 7]创建Series对象s1
import numpy as np
import pandas as pd
s1 = np.array([2,8,-5,6,7])
print(pd.Series(s1))

'''
为列表[2, 8, -5, 6, 7]
指定索引值['d', 'b', 'a', 'c', 'e'],
创建Series对象s2,
显示s2并使用index和values属性查看s2索引名和值
'''
s2=pd.Series([2,8,-5,6,7],index = ['d','b','a','c','e'])
print(s2)
print(s2.index)
print(s2.values)

'''
使用字典对象data创建DataFrame对象d1,
行索引值为['index0','index1','index2','index3','index4'],
显示d1并使用columns、index和values
属性查看d1列索引名、行索引名和值,字典对象data定义如下:
'''
data = {'column_a': ['ab', 'cd', 'ef', 'hi', 'jk'],
        'column_b': [23, 43, 54, 32, 62],
        'column_c': [1.4, 1.9, 3.2, 4.4, 5.6]}
a1 = pd.DataFrame(data)
a1.index = ['index0','index1','index2','index3','index4']
print(a1)
print(a1.columns)
print(a1.index)
print(a1.values)

#根据numpy的ndarray对象np1创建DataFrame对象d2并显示d2。
a1 = np.arange(10).reshape(5,2)
a = pd.DataFrame(a1)
a

'''
① 使用列表列名索引方法查看“column_a”列的内容。
② 使用列表列名索引方法查看“column_a”和“column_b”列的内容。
③ 使用索引切片查看“index0”至“index3”行的内容。
'''
data = {'column_a': ['ab', 'cd', 'ef', 'hi', 'jk'],
        'column_b': [23, 43, 54, 32, 62],
        'column_c': [1.4, 1.9, 3.2, 4.4, 5.6]}
a1 = pd.DataFrame(data)
a1.index = ['index0','index1','index2','index3','index4']
print(a1.column_a)
print(a1[['column_a','column_b']])
print('__________________________')
print(a1[:'index3'])

'''
使用loc方法和iloc方法查看
“index0”和“index3”行的内容、
“index2” 和“column_a”的内容、
“index0”和“index3”对应的
“column_a”和“column_c”的内容。
'''
print(a1.loc[['index0','index3']])
print(a1.loc[['index2'],['column_a']])
print(a1.loc[['index0','index3'],['column_a','column_c']])

'''
① 追加列“column_d”: [10, 20, 30, 40, 50]和
“column_e”:[0.5,0.7,0.6,0.3,0.1]。
'''
a1['column_d']=[10,20,30,40,50]
a1['column_e']=[0.5,0.7,0.6,0.3,0.1]
a1

#修改“column_d”列名为“new”
a1.rename(columns={'column_d':'new'},inplace = True)
a1

#删除列“column_e”
del a1['column_e']
a1

#① 创建DataFrame数据表对象stu和scoresheet,如下所示:
import numpy as np
import pandas as pd
s={
    'class':[1,2,3,1,2,2,2],
    'Major':['network ','network','hardware','hardware','software','hardware','hardware'],
    'Name':['Zhang San','Li si','Wang Laowu','hao Liu','gian Qi','Sun Ba','Hu Jiu']
}
stu=pd.DataFrame(s)
stu.index=[101,102,103,104,105,106,107]
print(stu)

scoresheet1={
    'Name':['Zhang san','Li si' ,'Wang Laowu','Zhao Liu' ,'gian gi','sun Ba'],
    'score':[98,76,84,70,93,83],
    'Subject':['Python',' C++','Python','C++','Python',' Java']
}
scoresheet=pd.DataFrame(scoresheet1)
scoresheet.index=[101,102,103,104,105,106]
print(scoresheet)

#stu按‘Major’和‘Class’升序排列,scoresheet按‘Score’降序排列,输出结果如下
import numpy as np
import pandas as pd
s={
    'class':[1,2,3,1,2,2,2],
    'Major':['network ','network','hardware','hardware','software','hardware','hardware'],
    'Name':['Zhang San','Li si','Wang Laowu','hao Liu','gian Qi','Sun Ba','Hu Jiu']
}
stu=pd.DataFrame(s)
stu.index=[101,102,103,104,105,106,107]
stu.sort_values(by=['Major','class'],axis=0,ascending=[True,True],inplace=True)
stu

scoresheet.sort_values(by='score',axis=0,ascending=False,inplace=True)
scoresheet

'''
scoresheet中修改‘zhao Liu’和‘Qian Qi’的‘Score’值为98,
并返回学生的‘Score’降序排名
,排名相同时取最小排名,输出结果如下:
'''
scoresheet.iloc[1,1]=98
scoresheet.iloc[5,1]=98
print(scoresheet.sort_index())
print(scoresheet.sort_values(by=['score']).rank(method='min',ascending=False).sort_index())

'''
scoresheet按‘Subject’分组
查看‘Python’分组信息
并对三门课程的‘Score’
进行描述统计分析,输出结果如下:
'''
print(scoresheet.groupby('Subject').get_group('Python'))
print(scoresheet.groupby('Subject').describe())

#使用concat函数将stu和scorsheet横向合并,输出结果如下
print(pd.concat([stu,scoresheet],axis=1).sort_index())

#使用merge函数将stu和scoresheet按‘Name’关键字合并,输出结果如下:
print(pd.merge(stu.sort_index(),scoresheet.sort_index(),on='Name'))

'''
(5)编写程序完成DataFrame数据表
对象stu和scoresheet的分类数据和缺失数据操作。
① 设置DataFrame数据表对象stu的
“Class”列为category类型数据,
追加列“Class_name”其对应“Class”列的值
:1-17物联网1班、2-17物联网2班、3-17物联网3班,
输出结果如下:

'''
stu['class'].astype('category')
class_name = pd.DataFrame({'class':[1,2,3],
                        'Class_name':['17物联网1班','17物联网2班','17物联网了班']},
                        index=[101,102,103],dtype='category')
stu_Class_name = pd.merge(stu,class_name,on='class',how='left',indicator=False,validate=None)
stu_Class_name.index=[101,102,103,104,105,106,107]
print(stu_Class_name)

#按照“Class_name”排序,要求排序顺序为: '17物联网2班','17物联网3班','17物联网1班',输出结果如下:
stu_Class_name['Class_name'] = stu_Class_name['Class_name'].cat.set_categories(['17物联网1班','17物联网2班','17物联网了班'])
scn = stu_Class_name.sort_values(by=['Class_name'],ascending=True)
scn

'''
scoresheet中修改‘Zhao Liu’
和‘Qian Qi’的‘Score’值
为缺失值,并使用线性插值法
填充该缺失值,输出结果如下:
'''
scoresheet.iloc[3,1]=None
scoresheet.iloc[4,1]=None
print(scoresheet.interpolate().sort_index())



'''
(1)导入matplotlib、numpy和pandas并解决中文乱码问题。
%matplotlib inline 
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
#设置rc参数显示中文标题,设置字体为SimHei国标黑体显示中文
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False   #设置正常显示字符
(2)在同一坐标系中绘制多种曲线,通过样式、宽度、颜色加以区分并设置标题、坐标轴名称。
x = np.linspace(0, 3, 200)  #产生从0到3均匀分布的200个浮点ndarray 
三条线段颜色取值为蓝、绿、青,编写程序输出如下图形:

'''
%matplotlib inline 
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False
x = np.linspace(0,3,200)
p0 = x
p1=np.square(x)
p2 = x*x*x
y=[p0,p1,p2]
plt.plot(x, p0, color="orange", linewidth=2.5, linestyle="-", label="y = x")
plt.plot(x, p1, color="red",  linewidth=2.5, linestyle="--", label="y = x^2")
plt.plot(x, p2, color="green",  linewidth=2.5, linestyle='dotted', label="y = x^3")
plt.legend(loc='upper left')
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.annotate(text='Here I am',xy=(1,1),xytext=(4,-0.5),\
            weight = 'bold',color='black',\
            arrowprops = dict(arrowstyle='-|>',connectionstyle='arc3',color='red'),\
            bbox = dict(boxstyle = 'round,pad=0.5',fc='yellow',ec = 'black',lw=1,alpha= 0.4))
plt.show()




#读入当前文件夹下的学生成绩文件“scoresheet.xlsx”
stuscore=pd.read_excel('scoresheet.xlsx',header=None,
                       names=['id','name','gender','english','math',
                        'ethnic theory','physics'] )

plt.figure(figsize=(11,7))
plt.subplots_adjust(hspace=0.6,wspace=0.2)
mpl.rcParams['font.size'] = 8; mpl.rcParams['figure.figsize'] = (12,9) 
plt.rcParams['font.sans-serif'] = ['SimHei']; plt.rcParams['axes.unicode_minus'] = False  


#创建一个2行2列的拼图
plt.subplot(221)
plt.xticks(np.arange(0,15,2));plt.yticks(np.arange(50,100,10))
plt.plot(stuscore.english,label='english score');plt.plot(stuscore.math,label='math score')
plt.plot(stuscore['ethnic theory'],label='ethnic theory score');plt.plot(stuscore.physics,label='physics score')
plt.legend(loc=8,frameon=False,bbox_to_anchor=(0.5, -0.4)) 
plt.title("学生期末各科成绩折线图")


plt.subplot(222);plt.bar(stuscore['name'],stuscore['physics'],width = 0.8)
plt.xticks(rotation=50);plt.title("学生期末物理成绩条形图")


plt.subplot(223);plt.xticks(np.arange(64,80,2));plt.ylim(70,91);plt.scatter(stuscore['ethnic theory'],stuscore['physics'],25)
plt.title("学生民族理论和物理成绩散点图")

plt.subplot(224);plt.pie(stuscore['gender'].value_counts(),labels=['男','女'],autopct="%1.1f%%");plt.title("学生性别饼图")
plt.show()



#词云
import numpy as np
import pandas as pd  
import matplotlib.pyplot as plt
import jieba
from wordcloud import WordCloud
%matplotlib inline

s=pd.read_csv('sanguo.csv',encoding='utf-8')
mylist=s['三国演义']#指定用于制图的文本,也可以使用列表或元组等序列。
word_list=[" ".join(jieba.cut(sentence)) for sentence in mylist]
new_text=' '.join(word_list) #将所有文本字符链接起来
wordcloud=WordCloud(font_path='./msyh/msyh.ttc', 
                    background_color="white",
                    width=2000,height=1000,
                    max_words=200).generate(new_text)
#wordcloud对象用于设置词云图的字体、背景颜色、最大词频数等。
plt.imshow(wordcloud)
plt.axis("off") #关闭显示坐标轴
plt.show()

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值