Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have the following code from the book python for finance. But the round function from numpy is causing an error like " return round(decimals, out)
TypeError: round() takes at most 2 arguments (3 given)"
anyone knows what I am doing wrong?
import numpy as np
import pandas as pd
import pandas.io.data as web
sp500 = web.DataReader('^GSPC', data_source='yahoo',
start='1/1/2000', end='4/14/2014')
sp500.info()
sp500['Close'].plot(grid=True, figsize=(8, 5))
sp500['42d'] = np.round(pd.rolling_mean(sp500['Close'], window=42), 2)
Based on the error message, it seems that in numpy 1.11.0, the rounding function looks like this:
try:
round = a.round
except AttributeError:
return _wrapit(a, 'round', decimals, out)
return round(decimals, out)
It looks like pandas.Series.round only takes two arguments (self, precision), but numpy is passing it an additional argument, out. Presumably this is either a bug or API change in pandas or numpy.
There are two simple workarounds I can see. The first is to just directly use the Series.round() function:
sp500['42d'] = pd.rolling_mean(sp500['Close'], window=42).round(2)
The other option is to just apply the numpy.round function to the underlying numpy array:
sp500['42d'] = np.round(pd.rolling_mean(sp500['Close'], window=42).values, 2)
Edit: Looks like this is a known issue. See the pandas github tracker, issue #12644.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
I am working on a course via Pluralsight called Building your first Python Analytics Solution. The current module is teaching about the IDE - IDLE. The demo I am following uses a prebuilt python file called price.py that is supposed to output a list of items along with the total price. Within the example the instructor is solving for a zero entry using except and continue, as show within the picture, which works when the instructor runs it. Course Example
But when I try to mirror the code:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
price_data = pd.read_csv('~/Desktop/price.csv')
print(price_data.head())
price_data = price_data.fillna(0)
print(price_data.head())
def get_price_info():
for index, row in price_data.iterrows():
total_price = row['Total_Price']
quantity = row['Quantity']
try:
price_of_a_unit = (total_price/quantity)
print(price_of_a_unit)
except ZeroDivisionError :
continue
get_price_info()
plt.bar(price_data.Things, height=price_data.Total_Price)
plt.title('Barplot of Things vs Total_Price')
plt.show()
I get the error 'continue' not properly in the loop.
The course is using Python IDLE 3.8.
The current version that I am running is IDLE 3.10.4.
I have repeatedly gone over the code in the screenshot and it seems to me that the code is exactly the same. I have also researched the error and still could not come up with a solution that will allow me to run the script. I am really new at this and would love to understand where the issue is.
Based on a point, that the code did not match the screen shot. I reloaded the original price.py file and mage the edits needed to make it match. If I am still missing something I would be grateful to know where the mistake is.
After doing some research on try catch blocks I was able to edit the code
try:
price_of_a_unit = (total_price/quantity)
print(price_of_a_unit)
except ZeroDivisionError:
print("Make sure no divisions by 0 are made.")
except NameError:
print("Make sure both numbers are defined.")
and get the code to run. Thank you
Your try-except block is indented incorrectly: it runs after your for loop completes and therefore the continue statement is outside of the loop (invalid).
# loop begins
for index, row in price_data.iterrows():
total_price = row['Total_Price']
quantity = row['Quantity']
# loop ends
# try/catch begins
try:
price_of_a_unit = (total_price/quantity)
print(price_of_a_unit)
except ZeroDivisionError:
continue # outside of a loop - invalid
# try/catch ends
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
sorry I deleted this code I do not need help
import numpy as np
import gym
import matplotlib
import matplotlib.pyplot as plt
import tensorflow as tf
from env.BeamEnv import BeamEnv
if statements are vital for an application. As they are part of Dijkstra 1966 model of structured programming ingredients (Sequence, Repeatation, Selection) which still applies today for other paradigm like OOP, POP, FP, FRP, ...
And you are not using them excessively (which could raise a red flag i.e switch statement).
However I would like to recommend to merge your two if conditions if you are not suppose render when you want to export frames. I don’t know what _render() function does but if it is only of use when you need to export frames, you should have put it in the main if to prevent calling unnecessary functions (init_plt() and _render())
if render and self.episode_count % self.sample_freq == 0:
self._init_plt()
self._render(obs)
self.export_frames()
self.episode_count += 1
If you adopt the above code I would like to put your conditions into a functions which returns a boolean.
if self.should_render(self.episode_count):
self.init_plt()
self._render(obs)
self.export_frames()
self.episode_count += 1
Still if you always use init_plt() and _render() together, you may consider, writing a wrapper function which calls them both. Just make the main logic of your code more readable. See Robert Martin (uncle bob) talks on clean codes.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to implement this fairly straightforward function as a CUDA kernel using Numba:
#nb.njit(parallel=True)
def sum_pixel_signals_cpu(pixels_signals, signals, index_map):
for it in nb.prange(signals.shape[0]):
for ipix in nb.prange(signals.shape[1]):
index = index_map[it][ipix]
start_tick = track_starts[it] // consts.t_sampling
for itick in nb.prange(signals.shape[2]):
itime = int(start_tick+itick)
pixels_signals[index, itime] += signals[it][ipix][itick]
This function works fine and the result is what I expect. I tried to implement it a CUDA-equivalent version with this piece of code:
#cuda.jit
def sum_pixel_signals(pixels_signals, signals, index_map):
it, ipix, itick = cuda.grid(3)
if it < signals.shape[0] and ipix < signals.shape[1]:
index = index_map[it][ipix]
start_tick = track_starts[it] // consts.t_sampling
if itick < signals.shape[2]:
itime = int(start_tick+itick)
cuda.atomic.add(pixels_signals, (index, itime), signals[it][ipix][itick])
Unfortunately, when I call the kernel, I get this not very helpful error message:
ERROR:numba.cuda.cudadrv.driver:Call to cuMemcpyDtoH results in UNKNOWN_CUDA_ERROR
---------------------------------------------------------------------------
CudaAPIError Traceback (most recent call last)
<ipython-input-14-3786491325e7> in <module>
----> 1 sum_pixel_signals[threadsperblock,blockspergrid](pixels_signals, d_signals, pixel_index_map)
I don't understand what I am doing wrong. Is there a way to at least debug this kind of error messages?
The problem was caused by the grid arguments written backwards... The correct way:
sum_pixel_signals[blockspergrid,threadsperblock](pixels_signals, d_signals, pixel_index_map)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have this code that I typed into Python and I'm getting "Syntax error: invalid syntax" for b=Od/T. Does it have to do with how it's defined? How can I fix it
import scipy.integrate as sci
import scipy.constant as scc
import math
import numpy as np
import matplotlib.pyplot as plt
from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')
def f(T):
n=6.022*(10**28)
Od=429
V=10**(-3)
ft=lambda x: ((x**4)*math.exp(x)/(((math.exp(x))-1**2))
b = Od/T
a=0
C=9*V*n((T/Od)**3)*scc.k*(sci.quad(ft,a, b.any(),limit=10))[0]
return C
T1=np.arange(5,500,1)
plt.plot(T1,f(T1),'r-')
You're missing a closing parentheses on the previous line:
ft=lambda x: ((x**4)*math.exp(x)/(((math.exp(x))-1**2))
# ^ This parenthesis is never closed.
Error in the line before that. You can try this.
fr=lambda x: (x**4)*math.exp(x)/((math.exp(x))-1**2)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I'm new in python and I'm trying to add an attribute to a maya light shape. The script should works like that: for each light.shape I've selected add a 'mtoa_constant_lightGroup' attribute:
import maya.cmds as pm
lightSelect= pm.ls (sl=True, dag=True, leaf=True)
for elem in lightSelect:
pm.addAttr (elem, ln='mtoa_constant_lightGroup', at=long, dv=0)
pm.setAttr (e=True, keyable=True, elem +'.mtoa_constant_lightGroup')
But when I run the script I've got this error:
Error: line 1: non-keyword arg after keyword arg
Any suggestions please.
In the following line from your code you have a positional argument after a keyword argument, which does not make sense.
pm.setAttr (e=True, keyable=True, elem +'.mtoa_constant_lightGroup')
# ---- here ----------------------^
fix it!
so as Martin said I had to move the keyword arguments to the end
then for the error " # Error: line 1: RuntimeError: file line 6: Type specified for new attribute is unknown." I needed to set at=long as a string, e.g.
`pm.addAttr (elem, ln='mtoa_constant_lightGroup', at="long", dv=0)`
The final scripts is this:
import maya.cmds as pm
lightSelect= pm.ls (sl=True, dag=True, leaf=True)
for elem in lightSelect:
pm.addAttr (elem, ln='mtoa_constant_lightGroup', at="long", dv=0)
pm.setAttr(elem +'.mtoa_constant_lightGroup', e=True, keyable=True)
thanks for all your helps