text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
Python : DataFrameGroupby.filter method filters the groups , and returns the DataFrame that contains the rows that passed the filter.But what can I do to obtain a new DataFrameGroupBy object instead of a DataFrame after filtration ? For example , let 's say I have a DataFrame df with two columns A and B. I want to obta... | Chaining grouping , filtration and aggregation |
Python : Hi heroku python people , I want my heroku app to access shared private libraries in my github account.So I would like to have a requirements.txt file that looks like this ... And I would like it to use a ssh key that I upload with heroku keys : add or have some mechanism to get a private key from the heroku c... | python | heroku | how to access packages over ssh |
Python : Problem : After running a line profiling of a data analysis code I have written , I have found that around 70 % of the total run time is concentrated in calls to two different array manipulation routines . I would eventually like to analyze data in a real-time fashion , so any optimization here would help sign... | Optimizing Array Element Shifting in Python / Numpy |
Python : I 'm working with a Python 2.x framework , and a recent version of the framework has moved some widely used base classes from module A to module B ( and the classes have been renamed to a clearer names in the process ) . Module A defines a backward compatible identifiers for the new class names . B.py : A.py :... | Deprecate usage of a class as a parent class in Python |
Python : I want to create many processes , each process runs 5 seconds later than a previous process , namely , the time interval between each process starts is 5 seconds , so that : run process 1wait 5 seconds run process 2wait 5 secondsrun process 3wait 5 seconds ... ..like : but I want to call do_something ( ) after... | how to fetch process from python process pool |
Python : What will that return ? <code> return self.var [ : ] | What does [ : ] do ? |
Python : When I do n't know how deeply the lists will nest , this is the only way I can think to do this . <code> def flattenList ( toFlatten ) : final= [ ] for el in toFlatten : if isinstance ( el , list ) : final.extend ( flattenList ( el ) ) else : final.append ( el ) return final | Is there a functional way to do this ? |
Python : Lets say I have the following list in python . It is ordered first by Equip , then by Date : What I want to do is collapse the list by each set where a given piece of Equipment 's job does not change , and grab the first and last date the equipment was there . E.g. , this simple example should change to : A co... | Pythonic way of collapsing/grouping a list to aggregating max/min |
Python : I 'd like to know the type of an instance obtained from super ( ) function . I tried print ( super ( ) ) and __print ( type ( super ( ) ) ) __The result is With those result , I was wondering how super ( ) .__init__ ( ) calls the correct constructor . <code> class Base : def __init__ ( self ) : passclass Deriv... | How do I get the instance method 's next-in-line parent class from ` super ( ) ` in Python |
Python : Since in Python variables are accessible outside of their loops and try-except blocks , I naively thought that this code snippet below would work fine because e would be accessible : In Python 2 ( 2.7 tested ) , it does work as I expected and the output is : However , in Python 3 I was surprised that the outpu... | Scope of caught exception instance in Python 2 and 3 |
Python : The gigaword dataset is a huge corpus used to train abstractive summarization models . It contains summaries like these : I want to process these summaries with spacy and get the correct pos tag for each token . The issue is that all numbers in the dataset were replaced with # signs which spacy does not classi... | Correct POS tags for numbers substituted with # # in spacy |
Python : I 'm interested in knowing how much time of my script runtime is spent on the CPU vs the GPU - is there a way to track this ? Looking for a generic answer , but if that 's too abstract one for this toy solution ( from keras 's multi_gpu_model examples ) would be great . <code> import tensorflow as tffrom keras... | How do I keep track of the time the CPU is used vs the GPUs for deep learning ? |
Python : My ultimate aim is to convert the below code in python to C # , but I 'd like to do it my self by learning the python syntax . I understand that the code is recursive.The code produces polynomials of degree n with k variables . More specifically the list of exponents for each variable.Here is the conversion I ... | Python to C # Code Explanation |
Python : This is the problem I am trying to solve : B : The Foxen 's Treasure There are N ( 1 ≤ N ≤ 4 ) Foxen guarding a certain valuable treasure , which you 'd love to get your hands on . The problem is , the Foxen certainly are n't about to allow that - at least , not while they 're awake . Fortunately , through car... | Solution works for sample data but online judge gives errors ? |
Python : I have an OrderedDictionary that contains rate values . Each entry has a date for a key ( each date happening to be the start of a yearly quarter ) , and the value is a number . Dates are inserted in order , from oldest to newest.My dictionary of rates is much larger than this , but this is the general idea . ... | Efficiently finding the previous key in an OrderedDictionary |
Python : I have a DataFrame with two columns and a little over one-hundred thousand elements.If I request the last element from my group , the function just hangs ! I killed it after 6 minutes ; top shows the CPU at 100 % the entire time.If I request the localtime column explicitly , this will at least return , though ... | Performance issues with groupby 's last in pandas |
Python : I would like to know why a file object opened using with statement or in a block , remains in scope after exit . Are < closed file > objects ever cleaned up ? <code> > > > with open ( 'test.txt ' , ' w ' ) as f : ... f.write ( 'test ' ) ... > > > f < closed file 'test.txt ' , mode ' w ' at 0x00E014F0 > > > > f... | Why does the context hang around after a with statement ? |
Python : I 'm programming in python on a pre-existing pylons project ( the okfn 's ckan ) , but I 'm a lisper by trade and used to that way of doing things.Please correct me if I make false statements : In pylons it seems that I should say $ paster serve -- reloadto get a web server that will notice changes . At that p... | Pylons REPL reevaluate code in running web server |
Python : I have the need to create a plugin system that will have dependency support and I 'm not sure the best way to account for dependencies . The plugins will all be subclassed from a base class , each with its own execute ( ) method . In each plugin class , I 'd planned to create a dependencies attribute as a list... | Calculating plugin dependencies |
Python : Given the following dataset as a pandas dataframe df : We perform the following steps : The desired output should look like this : The last step performs very poorly , possibly related to Pandas Issue # 20660My first intention was to convert all datetime objects to int64 , which leaves me with the question on ... | Efficiently aggregate a resampled collection of datetimes in pandas |
Python : Imagine there is a framework which provides a method called logutils.set_up ( ) which sets up the logging according to some config.Setting up the logging should be done as early as possible since warnings emitted during importing libraries should not be lost.Since the old way ( if __name__=='__main__ ' : ) loo... | Logging in a Framework |
Python : Simple code : Ok , in the resulting sets there are no duplicates.What if the object in the list are not int but are some defined by me ? What method does it check to understand if they are different ? I implemented __eq__ and __cmp__ with some objects but set does n't seems to use them : \Does anyone know how ... | What does the function set use to check if two objects are different ? |
Python : I 'm pretty new to programming and made a program to fetch inventory data from Team Fortress 2 players and put the inventory items into a dictionary with the steamid as the key and the list of items as the value.The problem I 'm running into is that after about 6000 entries into the dictionary the program has ... | Python dictionary eating up ram |
Python : I 'm thinking I need to use numpy or some other library to fill these arrays fast enough but I do n't know much about it . Right now this operation takes about 1 second on a quad-core Intel PC , but I need it to be as fast as possible . Any help is greatly appreciated . Thanks ! <code> import cvclass TestClass... | How can I speed up array generations in python ? |
Python : I have the following dataframe in pandas : I want to put condistion that if value in food column is null , the age and beverage will change into ' ' ( blank as well ) , I have wrote this code for that : but I keep getting error : ValueError : The truth value of a DataFrame is ambiguous . Use a.empty , a.bool (... | change specific values in dataframe if one cell in a row is null |
Python : I just realized that CPython seems to treat constant expressions , which represent the same value , differently with respect to constant folding . For example : For the second example constant folding is applied while for the first it is not though both represent the same value . It does n't seem to be related... | What are the specific rules for constant folding ? |
Python : I am not sure if this is a bug or a feature.I have a dictionary to be initialized with empty lists.Lets sayWhat I observed is if you append any item to any of the lists all the lists are modified . sets But when I do it manually using loop , setsI would think the second behavior should be the default . <code> ... | Python dictionary initialization ? |
Python : I am looking for a nice , efficient and pythonic way to go from something like this : ( 'zone1 ' , 'pcomp110007 ' ) to this : 'ZONE 1 , PCOMP 110007'without the use of regex if possible ( unless it does make a big difference that is.. ) . So turn every letter into uppercase , put a space between letters and nu... | Produce a string from a tuple |
Python : I have some code for calculating missing values in an image , based on neighbouring values in a 2D circular window . It also uses the values from one or more temporally-adjacent images at the same locations ( i.e . the same 2D window shifted in the 3rd dimension ) . For each position that is missing , I need t... | python - combining argsort with masking to get nearest values in moving window |
Python : I was coding a decoration ( for curiosity 's sake ) to make a class abstract in python . So far it looked like it was going to work , but I got an unexpected behavior.The idea for the decoration looks like this : Then , when using this decoration , it 's only needed to define a abstract methodBut when I test ,... | Python abstract decoration not working |
Python : I know that the pythonic way of concatenating a list of strings is to useBut how would I do this if I have a list of objects which contain a string ( as an attribute ) , without reassigning the string ? I guess I could implement __str__ ( self ) . But that 's a workaround that I would prefer not to use . <code... | Concatenating Strings from a List of Objects |
Python : I have two algorithms of finding primes , in Python . The inner loop of each one seems to be executed the same number of times , and is equally simple . However , one of them takes 10 times as much as the other . My question is : Why ? Is this some quirk of Python that can be optimized away ( how ? ) , or am I... | Why do two algorithms for finding primes differ in speed so much even though they seem to do the same number of iterations ? |
Python : I would like to create an object then add attributes to the object on the fly . Here 's some pseudocode EX1 : EX2 : the first page of this PDFIn Python is it possible to add attributes to an object on the fly ( similar to the two examples I gave ) ? If yes , how ? <code> a = object ( ) a.attr1 = 123a.attr2 = '... | Can you add attributes to an object dynamically ? |
Python : I came across this weird behaviour which happens only in an interactive Python session , but not when I write a script and execute it . String is an immutable data type in Python , hence : Now , the weird part : I have seen that having a whitespace in the string causes this behaviour . If I put this in a scrip... | Python : id ( ) behavior in the Interpreter |
Python : I am having some trouble with solving a problem I encountered.I have an array with prices : And a ( randomly ) generated array of Poisson distributed arrivals : Each single arrival should be associated with the price at the same index . So in the case above , the first element ( x [ 0 ] ) should be selected 4 ... | Fast way to select n items ( drawn from a Poisson distribution ) for each element in array x |
Python : Is it possible to add custom setuptools commands to a project by using the entry_points argument to the setup ( ) call ? For example , I 've added this to the setup ( ) call of a project : But I still get no abc command when I do python setup.py -- help-commands . Any ideas ? https : //pythonhosted.org/setupto... | Adding a setuptools command using ` entry_points ` |
Python : This is the basic Python example from https : //docs.python.org/2/library/multiprocessing.html # module-multiprocessing.pool on parallel processingwhich I ca n't run for some reason on my PC . When I try to execute the third block the program freezes . My OS is Windows 10 . I run the program on the Spyder IDE ... | Basic parallel python program freezes on Windows |
Python : This question stems from looking at the answers provided to this question regarding counting the number of zero crossings . Several answer were provided that solve the problem , but the NumPy appproach destroyed the others with respect to time.When I compared four of the answers however I notice that the NumPy... | Different results to counting zero-crossings of a large sequence |
Python : Take a look at this : It outputs : I was expecting the last line to be 345 , since I was expecting int ( 41063625 ** ( 1.0/3 ) ) to equal int ( 345.0 ) to in turn equal 345 , as the other two outputs suggest . However , this is evidently not the case . Can anyone give me any insight as to what 's going on here... | Python strange int behavior |
Python : I have a method : basically , a tornado coroutine.I am making a list such as : In trying to make this a list comprehension such as : I realized this was invalid syntax . It turns out you can do this using ( ) around the yield : Does this behavior ( the syntax for wrapping a yield foo ( ) call in ( ) such as ( ... | Why does adding parenthesis around a yield call in a generator allow it to compile/run ? |
Python : I have a decorated function ( simplified version ) : now I want to add this method to a pre-esisting class.when I call this method : I got : why does n't it propagate self ? <code> class Memoize : def __init__ ( self , function ) : self.function = function self.memoized = { } def __call__ ( self , *args , **kw... | add a decorate function to a class |
Python : This is the code example in my C # project.I have a python script which imports the .dll with this code example and I want to create this settings.SpecificValue variable within the python script.Is it somehow possible without making a function in C # which I can call within python code.In python I want to call... | Create a generic List from C # dll in python script |
Python : I 'm new to python . And something is confusing me today . Under the path c : \python\ , there are several folds . I edit a python script under this path , and run the code : It prints : But when I put the script in fold Daily which is under the path C : \python\ , and run code : It prints : Did they have the ... | What 's the difference between './ ' and '../ ' when using os.path.isdir ( ) ? |
Python : Title edit : capitalization fixed and 'for python ' added.Is there a better or more standard way to do what I 'm describing ? I want input like this : [ 1 , 1 , 1 , 0 , 2 , 2 , 0 , 2 , 2 , 0 , 0 , 3 , 3 , 0 , 1 , 1 , 1 , 1 , 1 , 2 , 2 , 2 ] to be transformed to this : [ 0 , 1 , 0 , 0 , 0 , 0 , 2 , 0 , 0 , 0 , ... | Grouping a series in Python |
Python : Once , after watching Mike Muller 's performance optimization tutorial ( I think this one ) , one thought started to live in my head : if performance matters , minimize accessing items in the loop by index , e. g. if you need to access x [ 1 ] multiple times in a loop for x in l - assign a variable to x [ 1 ] ... | For loop item unpacking |
Python : The % % cython command is pretty handy to create cython functions without building and using a package . The command has several options but I could n't find a way to specify compile time environmental variables there.I want the equivalent of : for the % % cython command.I already tried : But that throws an Ex... | Cython ipython magic with compile time environmental variables |
Python : I have the following rather simple snippet : This function takes a string s and delete all s [ start : end ] from s , where pairs of indices ( start , end ) are given in a list blocks.Is there a builtin function somewhere that does the same thing ? Update : There is an assumption in my code : blocks are sorted... | Python : delete substring by indices |
Python : Is it possible to produce a series which interpolates its value , for any given index . I have a predefined interpolation scheme I wish to prescribe and I 'd rather the caller did n't apply the interpolation themselves , to avoid any possibilities of error.The caller would receive i as a result and they could ... | Is it possible to construct a Pandas Series which auto-interpolates ? |
Python : I have two lists : The first one is a regular list which contains links of Sitemaps : The second list is nested and contains links which were indexed on the sitemaps and a date for every link : Now I want to merge the list with the nedted list based on the sitmap they came from like this : But with my code : T... | How to concatenate a list with a nested list ? |
Python : I am working on a problem that involves validating a format from within unified diff patch.The variables within the inner format can span multiple lines at a time , so I wrote a generator that pulls each line and yields the variable when it is complete.To avoid having to rewrite this function when reading from... | What is a good way to decorate an iterator to alter the value before next is called in python ? |
Python : I 've written the following backpropagation routine for a neural network , using the code here as an example . The issue I 'm facing is confusing me , and has pushed my debugging skills to their limit.The problem I am facing is rather simple : as the neural network trains , its weights are being trained to zer... | Why does this backpropagation implementation fail to train weights correctly ? |
Python : Possible Duplicate : What does python intern do , and when should it be used ? I am working with a program in python that has to correlate on an array with millions of string objects . I 've discovered that if they all come from the same quoted string , each additional `` string '' is just a reference to the f... | How do I make Python make all identical strings use the same memory ? |
Python : Base scenarioFor a recommendation service I am training a matrix factorization model ( LightFM ) on a set of user-item interactions . For the matrix factorization model to yield the best results , I need to map my user and item IDs to a continuous range of integer IDs starting at 0.I 'm using a pandas DataFram... | Appending pandas DataFrame with MultiIndex with data containing new labels , but preserving the integer positions of the old MultiIndex |
Python : I have such code : I want to get two lists , the first contains elements of ' a ' , where a [ ] [ 1 ] = 1 , and the second - elements where a [ ] [ 1 ] = 0 . So I can do such thing with two list comprehension : But maybe exists other ( more pythonic , or shorter ) way to do this ? Thanks for your answers . <co... | Python , working with list comprehensions |
Python : I have gone through the customization documentation here https : //django-taggit.readthedocs.io/en/latest/custom_tagging.html # genericuuidtaggeditembase I am using the following code , when I save the product through django admin , tables are getting populated properly but when I am reading a product , tags a... | django-taggit not working when using UUID |
Python : The problem is a bit complex . In fact , I am not trying to re-invent the wheel and since the back-end dev left I am trying my best not to destroy his code.But , I think this time I will need to change a lot of things . Or maybe the answer is quite simple and my lake of experience play against me.Basically , I... | Django views.py updating a pagination from a category selection in a class-based view |
Python : I have code which worked in Python 3.6 and fails in Python 3.8 . It seems to boil down to calling super in subclass of typing.NamedTuple , as below : The purpose of this super ( object , self ) .__repr__ call is to use the standard ' < __main__.Test object at 0x7fa109953cf8 > ' __repr__ instead of printing out... | ` super ` in a ` typing.NamedTuple ` subclass fails in python 3.8 |
Python : I 'm hide Gtk widget , then try to show it , but none of the methods `` show ( ) '' , `` show_all ( ) '' or `` show_now ( ) '' does't work . If not call `` hide ( ) '' widget shows.test.py : gui.glade : http : //pastebin.com/xKFt1v84 <code> python 3.5.2gtk3 3.20.8pygobject-devel 3.20.1 import gigi.require_vers... | GtkInfoBar does n't show again after hide |
Python : I 've come across recently a number of places in our code which do things like thisand I am more than a little confused as to why people would do that , rather than doingand so on.Here is a slightly anonymised function which does this , in full : It confuses the hell out of pylint ( 0.25 ) as well me.Is there ... | Why would people use globals ( ) to define variables |
Python : I have a large csv file with lines that looks likeI need to convert it so the ids are consecutively numbered from 0 . In this case the following would workMy current code looks like : Python dicts use a lot of memory sadly and my input is large . What can I do when the input is too large for the dict to fit in... | How to remap ids to consecutive numbers quickly |
Python : I have a two lists of strings like the following : The second list is longer , so I want to downsample it to the length of the first list by randomly sampling.However , I want to add a restriction that the words chosen from the second list must match the length distribution of the first list . So for the first... | Randomly select values from list but with character length restriction |
Python : I have a list that has elements in this form , the strings may change but the formats stay similar : I would like to transform it to the list below . You can see it would remove copies of the same occurrence of a string such as Eth - just having one occurrence in the new list and transforms numbers into x and ... | Transform list with regex |
Python : I have a dictionary comprised of product names and unique customer emails who have purchased those items that looks like this : I am trying to iterate over the values of each key and determine how many emails match in the other keys . I converted this dictionary to a DataFrame and got the answer I wanted for a... | Compare values of a dictionary and return a count of matching values |
Python : I am trying to make a python process that reads some input , processes it and prints out the result . The processing is done by a subprocess ( Stanford 's NER ) , for ilustration I will use 'cat ' . I do n't know exactly how much output NER will give , so I use run a separate thread to collect it all and print... | How to collect output from a Python subprocess |
Python : I have the following in python : where regex is a Regular Expression and string is a filled String . So I am trying to do the same in Scala , using regex.replaceAllIn ( ... ) function instead of pythonsub . However , I do n't know how to get the subgroups that match.Is there something similar to python functio... | How can I get subgroups of the match in Scala ? |
Python : Let 's consider any user-defined pythonic class . If I call dir ( obect_of_class ) , I get the list of its attributes : You can see 2 types of attributes in this list : built-in attributes , user defined.I need to override __dir__ so , that it will return only user defined attribltes . How I can do that ? It i... | Modifying built-in function |
Python : I would like to use numpy.random.choice ( ) but make sure that the draws are spaced by at least a certain `` interval '' : As a concrete example , I would prefer these be spaced by at least the interval+1 , i.e . 5+1=6 . In the above example , this condition is n't met : there should be another random draw , a... | Drawing random numbers with draws in some pre-defined interval , ` numpy.random.choice ( ) ` |
Python : Given a list I need to return a list of lists of unique items . I 'm looking to see if there is a more Pythonic way than what I came up with : Output : <code> def unique_lists ( l ) : m = { } for x in l : m [ x ] = ( m [ x ] if m.get ( x ) ! = None else [ ] ) + [ x ] return [ x for x in m.values ( ) ] print ( ... | Unique lists from a list |
Python : I 'm fairly new to programming and I 've been assigned a homework assignment that converts English text into Pig Latin.The code I have so far is : If I comment out the else aspect of the def vowel_index function , the if aspectthen works . If I leave it in the program , the if aspect no longer functions.I 've ... | ( Python ) If Else issue and list to string conversion issue |
Python : Observe : Similarly for column_stack and row_stack ( hstack behaves differently in this case but it also differs when used with broadcast ) . Why ? I 'm after the logic behind that rather than finding a way of `` repairing '' this behavior ( I 'm just fine with it , it 's just unintuitive ) . <code> In [ 1 ] :... | Why does numpy.broadcast `` transpose '' results of vstack and similar functions ? |
Python : I 'll preface this by saying this is a toy example - I do have motivations for doing this , as it sits in the middle of some other chained operations . I have a DataFrame something like I am trying to produce a new DataFrame consisting of two columns with the hosts being the index - one column being the values... | How to access a column whose name I can not access in chained operations |
Python : pyxl or interpy are using a very interesting trick to enhance the python syntax in a way : coding : from PEP-263orHow could I write my own coding : if I wanted to ? And could I use more than one ? <code> # coding : pyxlprint < html > < body > Hello World ! < /body > < /html > # coding : interpypackage = `` Int... | How does `` coding : pyxl '' work in Python ? |
Python : I warn in advance : I may be utterly confused at the moment . I tell a short story about what I actually try to achieve because that may clear things up . Say I have f ( a , b , c , d , e ) , and I want to find arg max ( d , e ) f ( a , b , c , d , e ) . Consider a ( trivial example of a ) discretized grid F o... | Evaluate array at specific subarray |
Python : I have a circulation pump that I check wither it 's on or off on and this is not by any fixed interval what so ever . For a single day that could give me a dataset looking like this where 'value ' represents the pump being on or off.The format is not that important and can be changed.What I do want to know is ... | How to calculate running time from status and time using python |
Python : I 'm using python 3.6 . I came across the below way to flatten the nested list using sum : which returns : What exactly is going on here ? Sum takes an iterable , in this case a list , and a start value . I do n't understand what python reads to flatten the list . <code> a = [ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ]... | How flattening a nested list using ` sum ( iterable , [ ] ) ` works ? |
Python : This question tells me how to check the version of Python . For my package I require at least Python 3.3 : but where/when should this check occur ? I want to produce the clearest possible error message for users installing via pip ( sdist and wheel ) or python setup.py install . Something like : <code> MIN_VER... | When/where should I check for the minimum Python version ? |
Python : I ca n't figure out what I 'm doing wrong here . My error is : ImproperlyConfigured at /admin/ 'CategoryAdmin.fields ' must be a list or tuple.Is n't the CategoryAdmin.fields a tuple ? Am I reading this wrong ? admin.py .. <code> class CategoryAdmin ( admin.ModelAdmin ) : fields = ( 'title ' ) list_display = (... | Is this not a tuple ? |
Python : Is there a way to list the PyPi package names which correspond to modules being imported in a script ? For instance to import the module scapy3k ( this is its name ) I need to usebut the actual package to install is scapy-python3 . The latter is what I am looking to extract from what I will find in the import ... | How to list the names of PyPI packages corresponding to imports in a script ? |
Python : I am trying to plot a graph with a logarithmic y-axis using pgf_with_latex , i.e . all text formatting is done by pdflatex . In my matplotlib rc Parameters I define a font to be used . Here comes my problem : The standard matplotlib.ticker.LogFormatterSciNotation formatter used math text and therefore a math f... | Is there a non-math version of matplotlib.ticker.LogFormatterSciNotation ? |
Python : I 'm having an issue with SWIG deleting temporary C++ objects too soon.Example output from a Python test script : The Deleting Buffer ( id = X ) is being generated from inside Buffer : :~Buffer ( ) C++ code , so we can see here that in the Funny business section , the C++ Buffer objects are getting deleted too... | SWIG , C++ , & Python : C++ temporary objects deleted too soon |
Python : The stockInfo.py contains : To execute the spider stockInfo in window 's cmd.Now all webpage of the url in resources/urls.txt will downloaded on the directory d : /tutorial . Then to deploy the spider into Scrapinghub , and run stockInfo spider.No error occur , where is the downloaded webpage ? How the followi... | How to save downloaded file when running spider on Scrapinghub ? |
Python : I 'm trying to work out how to speed up a Python function which uses numpy . The output I have received from lineprofiler is below , and this shows that the vast majority of the time is spent on the line ind_y , ind_x = np.where ( seg_image == i ) .seg_image is an integer array which is the result of segmentin... | Speed up numpy.where for extracting integer segments ? |
Python : Is there a reason in keyword claims to want an iterable object when what it truly wants is an object that implements __contains__ ? <code> > > > non_iterable = 1 > > > 5 in non_iterableTraceback ( most recent call last ) : File `` < input > '' , line 1 , in < module > TypeError : 'int ' object is not iterable ... | Why does the 'in ' keyword claim it needs an iterable object ? |
Python : I have a list of integers , in which some are consecutive numbers.What I have : myIntList = [ 21,22,23,24,0,1,2,3,0,1,2,3,4,5,6,7 ] etc ... What I want : I want to be able to split this list by the element 0 , i.e when looping , if the element is 0 , to split the list into separate lists.Then , after splitting... | split list by certain repeated index value |
Python : So , in numpy 1.8.2 ( with python 2.7.6 ) there seems to be an issue in array division . When performing in-place division of a sufficiently large array ( at least 8192 elements , more than one dimension , data type is irrelevant ) with a part of itself , behaviour is inconsistent for different notations.The o... | Unexpected behaviour in numpy , when dividing arrays |
Python : The numpy.dot docstring says : For 2-D arrays it is equivalent to matrix multiplication , and for 1-D arrays to inner product of vectors ( without complex conjugation ) . For N dimensions it is a sum product over the last axis of a and the second-to-last of bBut it does n't illustrate how numpy.dot calculate 1... | numpy.dot how to calculate 1-D array with 2-D array |
Python : I have some data , more or less like this : I want to turn it into a multilevel dict based on depth level ( key `` level '' ) : All I can come up with right now is this little piece of code ... which obviously breaks after few items : Originally sat down to it on Friday and it was supposed to be just a small e... | List of dicts to multilevel dict based on depth info |
Python : I have a class in python for a figure with attributes name , health , strength , stealth , agility , weapons and money . There is a shop in the game I 'm making to increase the value of any of the integer properties with a specific item . Each integer property can be increased by one of two different items wit... | How to increase an object attribute by a variable amount |
Python : I 'm having difficulties testing python functions thatreturn an iterable , like functions that areyielding or functions that simply return an iterable , like return imap ( f , some_iter ) or return permutations ( [ 1,2,3 ] ) .So with the permutations example , I expect the output of the function to be [ ( 1 , ... | Testing functions returning iterable in python |
Python : I was playing around with oauth2 to get a better understanding of it . For this reason , I 've installed offlineimap which should act as a third-party app . I 've found a nice way to read encrypted credentials here on stackexchange.Based on the linked post I 've modified/copied the following python script : In... | how to use gpg encrypted oauth files via Python for offlineimap |
Python : I would like to get the first letter with the maximum occurence of a string.For instance : I already have a working code , using OrdererDict ( ) to avoid automatic keys rearangement : but I 'm looking for a possible one-liner or more elegant solution ( if it 's possible ) .Note : I already tried to use Counter... | Get first letter with maximum occurence of a string |
Python : Suppose I have a dictionary Is there a data structure such that if I add the key-value pair 3:5 , to have it entered in the dictionary so that the keys are in sorted order ? i.e . I am aware of the collections.OrderedDict ( ) , but this only keeps the keys in the order in which they were added ( which is n't s... | Add keys in dictionary in SORTED order |
Python : I 've written a script in python to scrape all the names and the links associated with it from the landing page of a website using .get_links ( ) function . Then I 've created another function .get_info ( ) to reach another page ( using the links derived from the first function ) in order to scrape phone numbe... | Unable to print names in the right way in another function |
Python : Command dir ( __builtins__ ) just list all the 151 builtin libraries.However , It lists 68 built-in functions in 2 . Built-in Functions — Python 3.6.2 documentationI tried to get the functions from dir ( __builtins__ ) as the following steps : How to list the 68 built-in functions directly ? <code> len ( dir (... | Retrieve the 68 built-in functions directly in python ? |
Python : I have several series of lists of variable length with some nulls . One example is : but another contains all NaNs : I need the last item in each list , which is straightforward : But whilst getting to this I discovered that , without the isinstance , when the indexing chokes on the NaNs it does so differently... | pandas IndexError/TypeError inconsistency with NaN values |
Python : I am trying to install packages in an offline manner . However , when I downloaded all packages and tried to install these packages on another computer , some error has emerged as shown in the following figure . This seems like it is failed to install the `` dash-bootstrap-components '' package . How can I sol... | ERROR : No matching distribution found for wheel ( dash-bootstrap-components ) |
Python : This morning , I find myself writing something like : And was surprised that it gave me the expected result.I thought it would behave as : But it obviously did n't . It seems Python is treating the first statement differently from the second , which is nice but I could n't find any documentation or explanation... | What are the rules regarding chaining of `` == '' and `` ! = '' in Python |
Python : With json like below , which is an array of objects at the outer most level with further nested arrays with objects.I need to write this to a csv ( or .xlsx file ) what I 've tried so far ? This gives an empty file 'data_file.csv ' . Also how do I add headers to the CSV . I have the headers stored in a list as... | python nested json to csv/xlsx with specified headers |
Python : Suppose you have something likeHow does python behave relative to inheritance and method resolution order when you have a mixed hierarchy ? Does it obey the old traversal , the new traversal , a mix of the two depending on which branch of the hierarchy is walking ? <code> class C2 : passclass C1 ( object ) : p... | What happens if you mix old and new style classes in a hierarchy ? |
Python : I 'm trying trying to read some data in tensorflow , and then match it up with its labels . My setup is as follows : I have an array of english letters , `` a '' , `` b '' , `` c '' , `` d '' , `` e '' , ... I have an array of `` cyrillic '' letters , `` a '' , `` b '' , `` w , `` g '' , `` d '' , ... , I have... | Why are my examples and labels in the wrong order ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.