I have following dataframe:
Open High Low Close
Date
2000-02-01 6841.12 7052.22 6841.12 7050.46
2000-02-02 7063.57 7172.05 7038.71 7171.95
2000-02-03 7175.87 7354.56 7134.42 7354.26
I want to use functions from a different module. Say I call the module TA.py. In this module I enter following function:
def pan1(val):
return val > val.shift(1)
Now, I would like to apply this function for creating a new column in the dataframe:
import TA as TA
df['signal'] = np.where(TA.pan1(df.High),'Yes', 'No')
I receive the error message that module 'TA' has no attribute 'pan1'.
How can I reconstruct things that this is working (by keeping a module soultion)? If I use the same function in the same script (without the module) it is working.
EDIT: as explained in the comments, there are other functions in TA.py that I can import without problem. But this function pan1 seems to be wrong or not usable in the current set up. So, any hint what I should do different is welcome.
I post this as a possible solution although it should be more of a comment. I had the same issue with exactly the same error messages. The problem was banal: I forgot to save the module (after I added the "problematic" function). So I saved the module, I imported it again and everything worked.
Related
I want to replicate the code here, and I get the following error while running in Google Colab?
ImportError: cannot import name 'zero_gradients' from
'torch.autograd.gradcheck'
(/usr/local/lib/python3.7/dist-packages/torch/autograd/gradcheck.py)
Can someone help me with how to solve this?
This seems like it's using a very old version of PyTorch, the function itself is not available anymore. However, if you look at this commit, you will see the implementation of zero_gradients. What it does is simply zero out the gradient of the input:
def zero_gradients(i):
for t in iter_gradients(i):
t.zero_()
Then zero_gradients(x) should be the same as x.zero_grad(), which is the current API, assuming x is a nn.Module!
Or it's just:
if x.grad is not None:
x.grad.zero_()
Hey stackoverflow community,
i’m new to this forum and to python developing in general and have a problem with Alexa/ Python overriding the similar named variable from different files.
In my language learning skill I want Alexa to specifically link a “start specific practice” intent from the user to a specific practice file and from this file to import an intro, keyword and answer to give back to the user.
My problem with the importing, is that Python takes the last imported file and overrides the statements of the previous files.
I know I could probably change the variable names according to the practices but then wouldn't I have have to create a lot of individual handler functions which link the user intent to a specific file/function and basically look and act all the same?
Is there a better way more efficient of doing the specifying of those variables when importing or inside the functions?
import files and variables
from übung_1 import intro_1, keywords_1, real_1
from übung_2 import intro_1, keywords_1, real_1
working with the variables
def get_practice_response(practice_number):
print("get_practice_response")
session_attributes = {}
card_title = "Übung"
number = randint(0, len(keywords_1))
print(intro_1 + keywords_1[number])
speech_output = intro_1 + keywords_1[number]
session_attributes["answer"] = real_1[number]
session_attributes["practice_number"] = practice_number
session_attributes["keyword"] = keywords_1[number]
reprompt_text = "test"
should_end_session = False
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session))
I expected giving out the content of the specifically asked file and not variable content from the most recent files.
Sadly I haven't found a solution for this specific problem and hope someone could help me pointing me in the right direction.
Thank you very much in advance.
Might be easiest to import the modules like so:
import übung_1
import übung_2
The refer to the contents as übung_1.intro_1, übung_2.intro_1, übung_1.keywords_1 and so on.
As you point out, these two lines
from übung_1 import intro_1, keywords_1, real_1
from übung_2 import intro_1, keywords_1, real_1
don't work the way you want because the second import overrides the first. This has to happen because you can't have two different variables in the same namespace called intro_1.
You can get around this by doing
import übung_1
import übung_2
and then in your code you explicitly state the namespace you want:
print(übung_1.intro_1 + übung_1.keywords_1[number])
I'm trying to read the help on what various things do as I'm reading through code. I'm getting a bit lost in how to determine which module a function comes from. Here is my current example:
import quandl
import numpy as np
import matplotlib.pyplot as plt
amzn = quandl.get("WIKI/AMZN", start_date="2018-01-01", end_date="2019-01-01")
amzn_daily_close = amzn[['Adj. Close']]
amzn_daily_log_returns = np.log(amzn_daily_close.pct_change()+1)
monthly = amzn.resample('BM').apply(lambda x: x[-1])
So given this block of code, I can do help (quandl.get) to see information about that and help (np.log) to see what that does. But when I get to amzn.resample, where is that resample coming from? What should I be entering to see some help information on the resample stuff?
Look at the docstring of quandl.get method to get the help message about the return object. This will contain a statement as returns x-object. Googling about x-object will give you more info on this.
Alternatively, you can do this. To identify what is the object you can do the below.
amzn_type = type(amzn)
This gives the monthly object type. Googling for this type value will give you more insights about that object.Example -
a = 10
print(type(a))
The above code returns <class 'int'> output. Googling about int class in python3 will be helpful.
Inspection
You can 'inspect' the method to find the implementation:
import inspect
print(inspect.getfile(amzn.resample))
# /opt/miniconda/envs/stackoverflow/lib/python3.6/site-packages/pandas/core/generic.py
IDE
Or you can use a good IDE (e.g. PyCharm or IntelliJ) which supports you with some neat features:
Generally, these modules should be documented somewhere. They are usually "packaged" and made available on Python Package Index (pypi). You can search there for your package name and find the quandl page. That may have a link to the projects home page with more documentation.
I want to use mr. yasaichi's implementation of x-means written in Python for my master's thesis (yasaichi's x-means: https://gist.github.com/yasaichi/254a060eff56a3b3b858) . For the last few weeks there have been no problem and I have been running the algorithm several times on various data sets. Today, however, a weird error popped up:
AttributeError: 'KMeans' object has no attribute 'get_params'.
The error comes from line 75 in the yasaichi's implementation:
labels = range(0, k_means.get_params()["n_clusters"])
Originally I thought it was me who had done some weird changes to the code, but when I re-downloaded the original again it came up with the same error.
Any ideas?
It sounds like the KMeans object you are trying to use doesn't have the method get_params.
I just tested the code at https://gist.github.com/yasaichi/254a060eff56a3b3b858 and it worked for me. So, my best guess is that you are somehow overwriting the KMeans object or that your code is using a cached version of the code that defines the KMeans object.
To verify this, try adding print dir(k_means) before line 75 of yasaichi's implementation. You should also see that print k_means.__module__ should show sklearn.cluster.k_means_. If this is the case, the final thing I would recommend would be deleting the compiled Python file implementing the k_means_ module. This can be found by running the following:
import sklearn.cluster.k_means_
print sklearn.cluster.__file__
I'm trying to create a python program (using pyUNO ) to make some changes on a OpenOffice calc sheet.
I've launched previously OpenOffice on "accept" mode to be able to connect from an external program. Apparently, should be as easy as:
import uno
# get the uno component context from the PyUNO runtime
localContext = uno.getComponentContext()
# create the UnoUrlResolver
resolver = localContext.ServiceManager.createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", localContext)
# connect to the running office
ctx = resolver.resolve("uno:socket,host=localhost,port=2002;"
"urp;StarOffice.ComponentContext")
smgr = ctx.ServiceManager
# get the central desktop object
DESKTOP =smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
#The calling it's not exactly this way, just to simplify the code
DESKTOP.loadComponentFromURL('file.ods')
But I get an AttributeError when I try to access loadComponentFromURL. If I make a dir(DESKTOP), I've see only the following attributes/methods:
['ActiveFrame', 'DispatchRecorderSupplier', 'ImplementationId', 'ImplementationName',
'IsPlugged', 'PropertySetInfo', 'SupportedServiceNames', 'SuspendQuickstartVeto',
'Title', 'Types', 'addEventListener', 'addPropertyChangeListener',
'addVetoableChangeListener', 'dispose', 'disposing', 'getImplementationId',
'getImplementationName', 'getPropertySetInfo', 'getPropertyValue',
'getSupportedServiceNames', 'getTypes', 'handle', 'queryInterface',
'removeEventListener', 'removePropertyChangeListener', 'removeVetoableChangeListener',
'setPropertyValue', 'supportsService']
I've read that there are where a bug doing the same, but on OpenOffice 3.0 (I'm using OpenOffice 3.1 over Red Hat5.3). I've tried to use the workaround stated here, but they don't seems to be working.
Any ideas?
It has been a long time since I did anything with PyUNO, but looking at the code that worked last time I ran it back in '06, I did my load document like this:
def urlify(path):
return uno.systemPathToFileUrl(os.path.realpath(path))
desktop.loadComponentFromURL(
urlify(tempfilename), "_blank", 0, ())
Your example is a simplified version, and I'm not sure if you've removed the extra arguments intentionally or not intentionally.
If loadComponentFromURL isn't there, then the API has changed or there's something else wrong, I've read through your code and it looks like you're doing all the same things I have.
I don't believe that the dir() of the methods on the desktop object will be useful, as I think there's a __getattr__ method being used to proxy through the requests, and all the methods you've printed out are utility methods used for the stand-in object for the com.sun.star.frame.Desktop.
I think perhaps the failure could be that there's no method named loadComponentFromURL that has exactly 1 argument. Perhaps giving the 4 argument version will result in the method being found and used. This could simply be an impedance mismatch between Python and Java, where Java has call-signature method overloading.
This looks like issue 90701: http://www.openoffice.org/issues/show_bug.cgi?id=90701
See also http://piiis.blogspot.com/2008/10/pyuno-broken-in-ooo-30-with-system.html and http://udk.openoffice.org/python/python-bridge.html