我正在尝试将起点添加到流线图中。我在这里找到了一个使用起点的示例代码;在此链接中讨论了一个不同的问题,但 start_points 参数有效。我从这里获取了流线型示例代码(images_contours_and_fields 示例代码:streamplot_demo_features.py)。我不明白为什么我可以在一个代码中而不是另一个中定义起点。当我尝试在示例代码 (streamplot_demo_features.py) 中定义起点时,出现以下错误:
Traceback (most recent call last):
File "<ipython-input-79-981cad64cff6>", line 1, in <module>
runfile('C:/Users/Admin/.spyder/StreamlineExample.py', wdir='C:/Users/Admin/.spyder')
File "C:\ProgramData\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "C:\ProgramData\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "C:/Users/Admin/.spyder/StreamlineExample.py", line 28, in <module>
ax1.streamplot(X, Y, U, V,start_points=start_points)
File "C:\ProgramData\Anaconda2\lib\site-packages\matplotlib\__init__.py", line 1891, in inner
return func(ax, *args, **kwargs)
File "C:\ProgramData\Anaconda2\lib\site-packages\matplotlib\axes\_axes.py", line 4620, in streamplot
zorder=zorder)
File "C:\ProgramData\Anaconda2\lib\site-packages\matplotlib\streamplot.py", line 144, in streamplot
sp2[:, 0] += np.abs(x[0])
ValueError: …Run Code Online (Sandbox Code Playgroud) 我正在尝试将数据帧转换为 numpy 数组:
dataset = myset.values
X = np.array(dataset[0:,6:68], dtype="float32")
X[0:5,0:]
Run Code Online (Sandbox Code Playgroud)
这是一个错误:
-----------------------------------------------------------------------
----
ValueError Traceback (most recent call last)
<ipython-input-162-4b67608047d1> in <module>()
1 dataset = myset.values
----> 2 X = np.array(dataset[0:,6:68], dtype="float32")
3 X[0:5,0:]
ValueError: could not convert string to float: '62,6'
Run Code Online (Sandbox Code Playgroud)
哪里有问题?
我看过类似的问题,但我还没有找到可以帮助我的答案。我正在尝试使用点积方法找到两个向量之间的角度。
import math as m
import numpy as np
def mag(x):
return np.sqrt(np.sum(i**2 for i in x))
u = np.array([1,1,1])
v = np.array([-1,-1,-1])
theta = m.degrees(np.arccos(np.dot(u,v) / (mag(u) * mag(v))))
Run Code Online (Sandbox Code Playgroud)
它适用于大多数情况,但是当我将 u 和 v 设置为相距 180 度(如上所述)的向量时,我得到 ValueError: math domain error。我从 m.acos 切换到 np.arccos (如上所述),它返回 NaN 但本质上是相同的问题。我知道这是由浮点舍入错误导致的,该值略低于 -1,该值超出了 acos/arrcos 的域,但我不知道该怎么做。
print('theta = ', theta)
print('magnitude product = ', mag(u) * mag(v))
print('dot product = ', np.dot(u,v))
print('dot prod / mag prod = ', np.dot(u,v) / (mag(u) * mag(v)))
print('dot prod …Run Code Online (Sandbox Code Playgroud) 我正在尝试通过散景构建一个简单的条形图,但努力让它识别 x 轴并不断收到 ValueError ......我认为它需要采用字符串格式,但出于某种原因,无论我尝试什么都不会'工作。请注意,包含 Years 的列(从外观上看是浮动的)称为 RegionName,如果它看起来令人困惑。请看我下面的代码,有什么建议吗?
import pandas as pd
from bokeh.plotting import figure, output_file, show
from bokeh.models import ColumnDataSource
from bokeh.models.tools import HoverTool
import os
from bokeh.palettes import Spectral5
from bokeh.transform import factor_cmap
os.chdir("C:/Users/Vladimir.Tikhnenko/Python/Land Reg")
# Pivot data
def pivot2(infile="Land Registry.csv", outfile="SalesVolume.csv"):
df=pd.read_csv(infile)
table=pd.pivot_table(df,index=
["RegionName"],columns="Year",values="SalesVolume",aggfunc=sum)
table.to_csv(outfile)
return table
pivot2()
# Transpose data
df=pd.read_csv("SalesVolume.csv")
df=df.drop(df.columns[1:28],1)
df=pd.read_csv("SalesVolume.csv", index_col=0, header=None).T
df.to_csv("C:\\Users\Vladimir.Tikhnenko\Python\Land
Reg\SalesVolume.csv",index=None)
df=pd.read_csv("SalesVolume.csv")
source = ColumnDataSource(df)
years = source.data['RegionName'].tolist()
p = figure(x_range=['RegionName'])
color_map = factor_cmap(field_name='RegionName',palette=Spectral5,
factors=years)
p.vbar(x='RegionName', top='Southwark', source=source, width=1, …Run Code Online (Sandbox Code Playgroud) 我浏览了论坛并对我的代码进行了一些更改,但问题仍然存在。我确实进行了 migrate 和 makemigrations,甚至删除了 migrate 并重新创建了它。
我还在models.py代码中添加了default=0:
年龄 = 模型.PositiveIntegerField(默认值=0)
如果你能在这个问题上帮助我,我将不胜感激。这些是一些代码行,如果您需要任何其他信息,请告诉我。
这是错误:
ValueError at /basic_app/create/
invalid literal for int() with base 10: 'create'
Request Method: GET
Request URL: http://127.0.0.1:8000/basic_app/create/
Django Version: 2.1.2
Exception Type: ValueError
Exception Value:
invalid literal for int() with base 10: 'create'
Exception Location: C:\ProgramData\Miniconda3\envs\myDjanEnv\lib\site-packages\django\db\models\fields\__init__.py in get_prep_value, line 965
Python Executable: C:\ProgramData\Miniconda3\envs\myDjanEnv\python.exe
Python Version: 3.7.0
Python Path:
['C:\\Users\\Administrator\\Desktop\\django_lecture\\djan_advance\\advcbv',
'C:\\ProgramData\\Miniconda3\\envs\\myDjanEnv\\python37.zip',
'C:\\ProgramData\\Miniconda3\\envs\\myDjanEnv\\DLLs',
'C:\\ProgramData\\Miniconda3\\envs\\myDjanEnv\\lib',
'C:\\ProgramData\\Miniconda3\\envs\\myDjanEnv',
'C:\\ProgramData\\Miniconda3\\envs\\myDjanEnv\\lib\\site-packages']
Run Code Online (Sandbox Code Playgroud)
这是 __init__.py 文件,第 960-965 行:
Run Code Online (Sandbox Code Playgroud)def get_prep_value(self, value): from django.db.models.expressions import OuterRef value = …
开始学习Python,写了一个很简单的代码来练习try/except。
这是代码:
a = float(input('num1: '))
b = float(input('num2: '))
try:
result = a / b
except ValueError as e:
print ('error type: ', type (e))
print(result)
Run Code Online (Sandbox Code Playgroud)
每当我输入一个字母作为数字时,除了打印工作,但代码崩溃。
ZeroDivisionError&TypeError正在工作,但ValueError不是。
我什至将输入放在单独的 try/except 中,但它仍然无法正常工作。
我如何在此处以及在实际应用中处理此错误?
我试图在Python中做零对数.
from math import log
log(0)
Run Code Online (Sandbox Code Playgroud)
这引起了我的例外.
ValueError: math domain error
Run Code Online (Sandbox Code Playgroud)
我理解log一个负数在数学上是未定义的,这就是Python log可以引发这个ValueError异常的原因.但是为什么在用零值调用它时也会引发异常呢?它应该返回一个-inf值,我已经看到无限数字可以在Python中表示(如此处所示).
我可以在没有亲自对待的情况下处理这个问题吗?我的意思是在做这样的事情时亲自.
from math import log, inf
foo = ... # Random value.
if foo != 0: return log(foo)
else: return -inf
Run Code Online (Sandbox Code Playgroud) 我有一个字符串列表(CD_cent)像这样:
2.374 2.559 1.204
Run Code Online (Sandbox Code Playgroud)
我想用浮点数乘以这些数字.为此,我尝试将字符串列表转换为浮点列表,例如:
CD_cent2=[float(x) for x in CD_cent]
Run Code Online (Sandbox Code Playgroud)
但我总是得到错误:ValueError: could not convert string to float: '.'.我想这意味着,它无法将点转换为浮点数(?!)但是我怎么能解决这个问题呢?为什么不识别点?
我处理数据,对于某些示例,数据是有问题的。Python 提出了一个
ValueError:残差在初始点不是有限的。
是否有可能仅通过消息捕获值错误"Residuals are not finite in the initial point."?我试过:
try:
[code that could raise the error]
except Exception as e:
if e=='ValueError(\'Residuals are not finite in the initial point.\')':
[do stuff I want when the Residuals are not finite]
else:
raise e
Run Code Online (Sandbox Code Playgroud)
但它仍然一直引发错误。有没有办法实现我想象的样子?
谢谢
我有这个模型:
class News(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
)
thumb = models.ImageField(blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('news_detail', args=[str(self.id)])
Run Code Online (Sandbox Code Playgroud)
如果我添加博客文章并包含图片,一切都很好。如果我不包含图像并尝试在浏览器中查看帖子,则会出现此错误:
raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
ValueError: The 'thumb' attribute has no file associated with it.
[01/Apr/2019 08:11:48] "GET /news/ HTTP/1.1" 500 178129
Run Code Online (Sandbox Code Playgroud)
blank=True如果我不包含图像,我认为可以防止任何错误。我也尝试thumb = models.ImageField(blank=True, null=True)基于此问题但没有任何区别。
我怎样才能选择在我的博客文章中上传图片或不上传图片而不会出错?
附加信息
news_detail.html
{% extends 'base.html' %}
{% block content %} …Run Code Online (Sandbox Code Playgroud) valueerror ×10
python ×9
django ×2
numpy ×2
bokeh ×1
exception ×1
logarithm ×1
math ×1
matplotlib ×1
pandas ×1
plot ×1
python-3.x ×1
raise ×1
try-catch ×1
try-except ×1