Python学习笔记以及问题汇总

Python学习笔记以及问题汇总

1.Python-生成一定范围的随机小数

代码如下:

#Python-生成一定范围的随机小数
import random
A=0
B=1#小数的范围A ~ B
a=random.uniform(A,B)
C=2#随机数的精度round(数值,精度)
print(round(a,C))

解决写入csv中间隔一行空行问题

写入csv:

with open(birth_weight_file,'w') as f:
    writer=csv.writer(f)
    writer.writerow(birth_header)
    writer.writerows(birth_data)
    f.close()

这种写法最终的结果就是生成的csv文件每两行中间都有一行空白行,解决办法就是写入后面加上newline=’’

写法:

with open(birth_weight_file,'w',newline='') as f:
    writer=csv.writer(f)
    writer.writerow(birth_header)
    writer.writerows(birth_data)
    f.close()

2.Matplotlib 调整图表之间的距离

Adjusting the spacing of margins and subplots调整边距和子图的间距

subplots_adjust(self, left=None, bottom=None, right=None, top=None,wspace=None, hspace=None)
参数含义
left = 0.125# the left side of the subplots of the figure图片中子图的左侧
left = 0.125图片中子图的左侧
right = 0.9# the right side of the subplots of the figure图片中子图的右侧
bottom = 0.1# the bottom of the subplots of the figure图片中子图的底部
top = 0.9# the top of the subplots of the figure图片中子图的顶部
wspace = 0.2# the amount of width reserved for space between subplots,pressed as a fraction of the average axis width#为子图之间的空间保留的宽度,平均轴宽的一部分
hspace = 0.2# the amount of height reserved for space between subplots, # expressed as a fraction of the average axis height#为子图之间的空间保留的高度,平均轴高度的一部分加了这个语句,子图会稍变小,因为空间也占用坐标轴的一部分

3.numpy和pandas对于数据的处理应该注意:

  1. df[year]= df[year].str.replace(“万”,"") #对一列数据进行处理
  2. df[year] = df[year].astype(np.float) #改变这一列的数据类型,注意磁珠的np后面用的是‘.’,而不是’,‘!!!!!

4.在读取csv文件的时候,默认会自动添加新的一列,Unnamed:0

解决方案:

read_csv()时候,设置index_col=0即可。

在写入csv文件的时候,默认会自动加入新的一列,Unnamed:0

解决方案:

to_csv()时候,设置index=False。或者加上index=True, index_label=“id”

5.csv文件合并

1.使用 pd.concat()
pandas合并concat

axis合并方向

axis=0横向合并
axis=1纵向合并
df1 = pd.DataFrame(np.ones((3,4))*0, columns=['a','b','c','d'])
df2 = pd.DataFrame(np.ones((3,4))*1, columns=['a','b','c','d'])
df3 = pd.DataFrame(np.ones((3,4))*2, columns=['a','b','c','d'])

res=pd.concat([df1,df2,df3],axis=0)
print(res)

a b c d
0 0.0 0.0 0.0 0.0
1 0.0 0.0 0.0 0.0
2 0.0 0.0 0.0 0.0
0 1.0 1.0 1.0 1.0
1 1.0 1.0 1.0 1.0
2 1.0 1.0 1.0 1.0
0 2.0 2.0 2.0 2.0
1 2.0 2.0 2.0 2.0
2 2.0 2.0 2.0 2.0

res1=pd.concat([df1,df2,df3],axis=1)
 a    b    c    d    a    b    c    d    a    b    c    d

0 0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0 2.0 2.0 2.0 2.0
1 0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0 2.0 2.0 2.0 2.0
2 0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0 2.0 2.0 2.0 2.0
————————————————
原文链接:https://blog.csdn.net/changzoe/article/details/78810437

2.使用 pd.merge():横向合并必须指定key

6.箱型图
import matplotlib.pyplot as plt
import pandas as pd
fg,ax=plt.subplots()
f=ax.boxplot([dt1,dt2,dt3],meanline=True,showmeans=True)

boxplot()
x:指定要绘制箱线图的数据;
notch:是否是凹口的形式展现箱线图,默认非凹口;
sym:指定异常点的形状,默认为+号显示;
vert:是否需要将箱线图垂直摆放,默认垂直摆放;
whis:指定上下须与上下四分位的距离,默认为1.5倍的四分位差;
positions:指定箱线图的位置,默认为[0,1,2…];
widths:指定箱线图的宽度,默认为0.5;
patch_artist:是否填充箱体的颜色;
meanline:是否用线的形式表示均值,默认用点来表示;
showmeans:是否显示均值,默认不显示;
showcaps:是否显示箱线图顶端和末端的两条线,默认显示;
showbox:是否显示箱线图的箱体,默认显示;
showfliers:是否显示异常值,默认显示;
boxprops:设置箱体的属性,如边框色,填充色等;
labels:为箱线图添加标签,类似于图例的作用;
filerprops:设置异常值的属性,如异常点的形状、大小、填充色等;
medianprops:设置中位数的属性,如线的类型、粗细等;
meanprops:设置均值的属性,如点的大小、颜色等;
capprops:设置箱线图顶端和末端线条的属性,如颜色、粗细等;
whiskerprops:设置须的属性,如颜色、粗细、线的类型等;
————————————————

原文链接:https://blog.csdn.net/shulixu/article/details/86551482

e.g. 使用matplotlib库画箱线图

我们上面介绍了使用pandas画箱线图,几句命令就可以了。但是稍微复杂点的可以使用matplotlib库。matplotlib代码稍微复杂点,但是很灵活。细心点同学会发现pandas里面的画图也是基于此库的,下面给你看看pandas里面的源码:
Python数据可视化:箱线图多种库画法

通过源码可以看到pandas内部也是通过调用matplotlib来画图的。那下面我们自己实现用matplotlib画箱线图。

我们简单模拟一下,男女生从20岁,30岁的花费对比图,使用箱线图来可视化一下。
    import numpy as np 
    import matplotlib.pyplot as plt 
    fig, ax = plt.subplots() # 子图 
    def list_generator(mean, dis, number): # 封装一下这个函数,用来后面生成数据 
     return np.random.normal(mean, dis * dis, number) # normal分布,输入的参数是均值、标准差以及生成的数量 
    # 我们生成四组数据用来做实验,数据量分别为70-100 
    # 分别代表男生、女生在20岁和30岁的花费分布 
    girl20 = list_generator(1000, 29.2, 70) 
    boy20 = list_generator(800, 11.5, 80) 
    girl30 = list_generator(3000, 25.1056, 90) 
    boy30 = list_generator(1000, 19.0756, 100) 
    data=[girl20,boy20,girl30,boy30,] 
    ax.boxplot(data) 
    ax.set_xticklabels(["girl20", "boy20", "girl30", "boy30",]) # 设置x轴刻度标签 
    plt.show() 

在这里插入图片描述

7plt乱码问题

解决方法:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
8.python,panda concat问题

报错如下:

Type Error:cantnot concatenate object of type '<class ' pandas.core.indexing._LocIndexer '>';

在这里插入图片描述
在这里插入图片描述
原因是一个csv对象 orig_df =panda.read_csv(’###’),中存在一个函数loc刚好和orig_df数据中的列名同名。

9.成功解决ValueError: attempted relative import beyond top-level package

原因是使用“…”或者“.”
例如:

from  ..TestModel import Test

也就是差不多跨级引用!!
在这里插入图片描述 比如上述的这种文件目录
如果想要在testdb.py文件里,使用models.py中的函数:

 import sys
sys.path.append("..")
#添加上述代码
from django.http import HttpResponse
import TestModel
#数据库操作
def testdb(request):
    test1 = TestModel.models.Test(name='runoob')
    test1.save()
    return HttpResponse("<p>数据添加成功!</p>")

#这样就可以使用TestModel下面的models.py
10. 报错:TemplateDoesNotExist at /login/ 如何修改templates路径

Django运行的时候报错,这种错误的原因是在setting.oy文件中没有加入html文件夹所在的路径,所以加入就行了:

setting.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR+"/templates",],
        # 添加html文件所在的文件夹
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
11.提交表单报错:RuntimeError: You called this URL via POST, but the URL doesn’t end in a slash and you have A

提交表单报错:RuntimeError: You called this URL via POST, but the URL doesn’t end in a slash and you have APPEND_SLASH set.
解决方法:

RuntimeError: You called this URL via POST, but the URL doesn’t end in a slash and you have APPEND_SLASH set.
提示form的action地址最后不是/结尾的,而且APPEND_SLASH的值是Ture

将from的action地址改为/结尾的就可以了
或者
修改settings:APPEND_SLASH=False

12 url(r’^$’,views.index_view) AttributeError: module ‘views’ has no attribute ‘index_view’

views没有对应的函数(function)
解决方法:导入views函数出错
在这里插入图片描述

#这是错误的在urls.py文件中
import views

#正确的为
from . import views

13.django项目中的子路由的配置:

切记不要在一个urls.py 中使用path,另一个子路由中使用url。会出现,访问路径错误的情况。

14 .(1)django 中如何引入css ,js 文件?

https://blog.csdn.net/zxyhfdl/article/details/81907021?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase

值得注意的是。每个人的放置css,js 的父文件夹的位置是不同的所以引用的文件路径应该加上父亲的文件夹名。

14.(2)adango中如何引入echarts.min.js,步骤像上面的一样,不过更为简单的是直接拖入css文件夹就行了。其中有两个问题:
1.引入后显示echarts.min.js 文件中存在错误,get***is NULL.其实就是没后获得容器,也就是你初始化echart的第一步出错了:
var myChart = echarts.init(document.getElementById('main'));

这里是byid,所以你的容器的应该有main的id。

2.第二的问题就是由于没有设置main容器的大小,导致显示失败,如何确=确定是不是这个问题,只要你在显示的最后异步加上console.log(“结束了”)。看看js文件是否执行到最后的这个位置。

如何做呢?可以直接在css中设置容器大小。更为推荐的是在js中动态的添加一个div,并且设大小。

15Error: [WinError 10013] 以一种访问权限不允许的方式做了一个访问套接字的尝试。

解决方法:端口占用,改一下:python manage.py runserver 0.0.0.0:8001

16. python3中的__unicode__()不起作用,用__str__()就可以

关于__unicode__ 参考:
https://blog.csdn.net/qq13650793239/article/details/102638309

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Shanshan yuan

一个关注于技术与生活的学生

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

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

打赏作者

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

抵扣说明:

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

余额充值