text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
Python : Consider the following image , stored as a numpy array : Zeros represent background pixels , 1,2,3 and 4 represent pixels that belong to objects . You can see that objects always form contiguous islands or regions in the image . I would like to know the distance between every pair of objects . As distance meas... | Pairwise Distances Between Two `` islands '' / '' connected components '' in Numpy Array |
Python : I 'm getting a very odd error using a basic shortcut method in python . It seems , unless I 'm being very stupid , I get different values for A = A + B , and A += B . Here is my code : This basically just calculates the covariance of a vector autoregression . So for : I get : This is correct I believe ( agrees... | Python numpy addition error |
Python : I recently learned that Python has not only a module named ctypes , which has a docs page , but also a module named _ctypes , which does n't ( but is nonetheless mentioned a few times in the docs ) . Some code on the internet , like the snippet in this Stack Overflow answer , uses this mysterious undocumented ... | ctypes vs _ctypes - why does the latter exist ? |
Python : I have a 2-dimensional array of integers , we 'll call it `` A '' . I want to create a 3-dimensional array `` B '' of all 1s and 0s such that : for any fixed ( i , j ) sum ( B [ i , j , : ] ) ==A [ i.j ] , that is , B [ i , j , : ] contains A [ i , j ] 1s in it the 1s are randomly placed in the 3rd dimension .... | quickly calculate randomized 3D numpy array from 2D numpy array |
Python : I 'm pretty new to Python , and I have written a ( probably very ugly ) script that is supposed to randomly select a subset of sequences from a fastq-file . A fastq-file stores information in blocks of four rows each . The first row in each block starts with the character `` @ '' . The fastq file I use as my i... | How can I make my Python script faster ? |
Python : Is it possible to declare a number in Python as Neither seem to work of course . How do you emphasize things like these , for clarity in Python ? Is it possible ? <code> a = 35_000a = 35,000 | Declaring a number in Python . Possible to emphasize thousand ? |
Python : Let 's quote numpy manual : https : //docs.scipy.org/doc/numpy/reference/arrays.indexing.html # advanced-indexingAdvanced indexing is triggered when the selection object , obj , is a non-tuple sequence object , an ndarray ( of data type integer or bool ) , or a tuple with at least one sequence object or ndarra... | Why does operating on what seems to be a copy of data modify the original data ? |
Python : I want to print the contents of a file to the terminal and in the process highlight any words that are found in a list without modifying the original file . Here 's an example of the not-yet-working code : As it is , only the last item in the list , regardless of what it is or how long the list is , will be hi... | Finding and substituting a list of words in a file using regex in Python |
Python : And I print a , Also I print a [ 1 ] [ 0 ] What is [ ... ] ? and when I print a [ 1 ] [ 0 ] , print 2 , not [ ... ] ? <code> a = [ 2 ] a.append ( a ) [ 2 , [ ... ] ] 2 | python garbage collection about list append itself |
Python : I 've the below dictionary ( Geojson ) : What would be the easiest way to make it into as below , by moving certain values to new keys within properties.Any feedback would be helpful.Thanks . <code> 'properties ' : { 'fill ' : ' # ffffff ' , 'fill-opacity ' : 1 , 'stroke ' : ' # ffffff ' , 'stroke-opacity ' : ... | Shifting values from one key to another key in python dictionary |
Python : I am using the pyo3 rust crate ( version 0.11.1 ) in order to port rust code , into cpython ( version 3.8.2 ) code . I have created a class called my_class and defined the following functions : new , __str__ , and __repr__.TL ; DR : The __str__ function exists on a class ported from rust using the pyo3 crate ,... | __str__ function of class ported from rust to python using pyo3 does n't get used in print |
Python : I 'm trying to nice print some divisions with Sympy but I noticed it did n't display aligned.Reason/fix for this ? EDIT : I did a lot of reverse-engineering using inspect.getsource and inspect.getsourcefile but it did n't really help out in the end.Pretty Printing in Sympy seems to be relying on the Prettyprin... | Not aligned Sympy 's nice pritting of division |
Python : Do numpy arrays keep track of their `` view status '' ? What I am looking for is numpy.isview ( ) or something.I want this for code profiling to be sure that I am doing things correctly and getting views when I think I am . <code> import numpya = numpy.arange ( 100 ) b = a [ 0:10 ] b [ 0 ] = 100print a [ 0 ] #... | Can you tell if an array is a view of another ? |
Python : Is there any possible way to achieve a non-lazy left to right invocation of operations on a list in python ? e.g . scalaWhile I realize many folks will not prefer the above syntax , I like the ability to move left to right and add arbitrary operations as we go.The python for comprehension is imo not easy to re... | Left to right application of operations on a list in python3 |
Python : How exactly does the min function work for lists in python ? For example , gives num2 as the result . Is the comparison value based or length based ? <code> num = [ 1,2,3,4 , [ 1,2,3 ] ] num2 = [ 1,2,3,4,5 ] min ( num , num2 ) | Comparison on the basis of min function |
Python : I have a nested dictionary whose structure looks like thisEvery key is a string and every value is a dict.I need to replace every empty dict with `` '' . How would I go about this ? <code> { `` a '' : { } , '' b '' : { `` c '' : { } } } | Replace empty dicts in nested dicts |
Python : I have two lists . The first list is already sorted ( by some other criteria ) such that the earlier in the list , the better.The second list is a list of allowed values : I would like to select the highest sorted value that exists in the allowedList , and I 'm only coming up with silly ways of doing this . Th... | Finding first instance of one list in a second list |
Python : The code below works but each time you run a program , for example the notepad on target machine , the prompt is stuck until I quit the program.How to run multiple programs at the same time on target machine ? I suppose it can be achieved with either the threads or subprocess modules , but I still can not use ... | Concurrency with subprocess module . How can I do this ? |
Python : Jump to edit to see more real-life code example , that does n't work after changing the query orderHere are my models : Now , create 2 instances each : If I 'll query for only one model with annotations , I get something like that : This is correct behavior . The problem starts , when I want to get union of th... | Incorrect results with ` annotate ` + ` values ` + ` union ` in Django |
Python : I 'm trying to figure out the best way to design a couple of classes . I 'm pretty new to Python ( and OOP in general ) and just want to make sure that I 'm doing this right . I have two classes : `` Users '' and `` User '' .If I want to retrieve my users , I use : '' users.users '' seems to be a bit redundant... | Python newbie class design question |
Python : I am doing normalization for datasets but the data contains a lot of 0 because of padding.I can mask them during model training but apparently , these zero will be affected when I applied normalization.from sklearn.preprocessing import StandardScaler , MinMaxScalerI am currently using the Sklearn library to do... | mask 0 values during normalization |
Python : I 've coded for several months in Python , and now i have to switch to Java for work 's related reasons . My question is , there is a way to simulate this kind of statementwithout defining an additional isIn ( ) -like boolean function that scans list_name in order to find var_name ? <code> if var_name in list_... | Simulate if-in statement in Java |
Python : I am often tempted not to create a new list when using list comprehensions , because if the list is huge , it would mean more space needed to compute ( the way I understand it the list is not bieng aliased int his case , a new memory space is created for the new list ) As an illustrative example ( this could b... | List comprehension and copies of types |
Python : I am trying to switch two elements in the string while keeping all the other characters untouched . Here is an example : Original string : Required output : Notice that element after A* and B* are switched.I was able to compile a RegEx pattern that gives me elements to replace like following : After this stage... | How to switch two elements in string using Python RegEx ? |
Python : I 'm trying to extract the tabular contents available on a graph in a webpage . The content of those tables are only visible when someone hovers his cursor within the area . One such table is this one.Webpage addressThe graph within which the tables are is titled as EPS consensus revisions : last 18 months.I '... | Trouble parsing tabular items from a graph located in a website |
Python : I 'm looking for a way to efficiently get an array of booleans , where given two arrays with equal size a and b , each element is true if the corresponding element of a appears in the corresponding element of b.For example , the following program : Should printKeep in mind this function should be the equivalen... | Pythonic and efficient way to do an elementwise `` in '' using numpy |
Python : Google Play ecosystem allows ratings data to be accessible from bucket , i.e . cloud storage.While I can successfully download CSV from Play developer 's console and process it , the file is in utf-16 encoding . Here are the first 180 bytes : or decoded : However , when I try to access ratings via cloud storag... | Can not parse Google Play app ratings data |
Python : I have a list containing thousands of sets similar to this : each set in the list look something like this : I would like to do the set operation : X- ( YUZUAUB ... ... etc ) for every set in the list , for example , this would look something like this : after applying this operation on all elements in set_lis... | set operation on a list of elements |
Python : I have the following code snippet which i needed to ( massively ) speed up . As is , it 's hugely inefficient.Disassembled : is the outputis a list of tuples in the form ( [ ... ] , number_of_packages ) is the number of packages I need to reach . I can combine as many elements of the list `` input_list '' as I... | Can pythons lambda be used to change the inner working of another function ? |
Python : My Django webapp lets users download text files that are generated on the fly : I installed Django Debug Toolbar ( 0.11.0 , since I can not get 1.0.1 to work ) , but when I click to make the download , the toolbar does n't show info about the file that was downloaded , presumably because that is a separate pag... | Django debug toolbar : how do I profile a file download ? |
Python : I am a beginner and just started learning Python couple days ago ( yay ! ) so i 've come across a problem . when i run , this code outputs everything but the text ( txt in file is numbers 0-10 on seperate lines ) <code> def output ( ) : xf=open ( `` data.txt '' , `` r '' ) print xf print ( `` opened , printing... | Reading from file |
Python : When trying the following script in Python 2 , its output is and in Python 3 , the script its output is , What may be the reason for that ? <code> a = 200 print type ( a ) < type 'int ' > a = 200print ( type ( a ) ) < class 'int ' > | Difference of type ( ) function in Python 2 and Python 3 |
Python : I have a a nested list and I 'm trying to get the sum and print the list that has the highest numerical value when the individual numbers are summed togetherI 've been able to print out the results but I think there should be a simple and more Pythonic way of doing this ( Maybe using a list comprehension ) . H... | What is the proper way to print a nested list with the highest value in Python |
Python : The upshot of the below is that I have an embarrassingly parallel for loop that I am trying to thread . There 's a bit of rigamarole to explain the problem , but despite all the verbosity , I think this should be a rather trivial problem that the multiprocessing module is designed to solve easily . I have a la... | parallelized algorithm for evaluating a 1-d array of functions on a same-length 1d numpy array |
Python : I 'm testing a CreateAPIView with an APITestCase class . Things are working as expected as an anonymous user , but when I login ( ) as a user , I get a 405 HttpResponseNotAllowed exception . I 'm able to successfully create an object while authed as a user through the django-rest-framework web frontend . I 'm ... | 405 error when testing an authed django-rest-framework route |
Python : I 'm appending some weather data ( from json- dict ) - in Japanese to DataFrame.I would like to have something like this But I have thisHow Could I change the Codes to make it like that ? Here is the code <code> 天気 風 0 状態 : Clouds 風速 : 2.1m 1 NaN 向き : 230 天気 風 0 状態 : Clouds NaN 1 NaN 風速 : 2.1m 2 NaN 向き : 230 d... | Add values to existing rows -DataFrame |
Python : I am writing a program which stores some JSON-encoded data in a file , but sometimes the resulting file is blank ( because there was n't found any new data ) . When the program finds data and stores it , I do this : Of course , if the file is blank this will raise an exception , which I can catch but does not ... | Remove a JSON file if an exception occurs |
Python : I have a 100000000x2 array named `` a '' , with an index in the first column and a related value in the second column . I need to get the median values of the numbers in the second column for each index . This is how I colud do it with a for statement : Obviously it 's too slow with the for iteration : any sug... | dealing with arrays : how to avoid a `` for '' statement |
Python : I have an inventory journal that contains products and their relative inventory qty ( resulting_qty ) as well as the loss/gain every time inventory is added or subtracted ( delta_qty ) . The issue is that inventory records do not get updated daily , rather they are only updated when a change in inventory occur... | Need to expand an inventory journal ( log ) pandas dataframe to include all dates per product id |
Python : I am wondering if python has its error report message equivalent to $ ! in perl ? Anyone who could give me an answer will be greatly appreciated.Added : When Exception occurs , I got something like this . If I apply try and catch block , I can catch it and use sys.exit ( message ) to log the message . But , is... | does python has its error report message like $ ! in perl |
Python : I have a dataframe of shop names that I 'm trying to standardize . Small sample to test here : I set up a regex dictionary to search for a string , and insert a standardized version of the shop name into the column standard . This works fine for this small dataframe : The problem is I have about SIX million ro... | How to speed up multiple str.contains searches for millions of rows ? |
Python : What is the best way to copy a table that contains different delimeters , spaces in column names etc . The function pd.read_clipboard ( ) can not manage this task on its own.Example 1 : Expected result : EDIT : Example 2 : Expected result : I look for a universal approach that can be applied to the most common... | Parse prettyprinted tabular data with pandas |
Python : I 'm using sklearn pipelines to build a Keras autoencoder model and use gridsearch to find the best hyperparameters . This works fine if I use a Multilayer Perceptron model for classification ; however , in the autoencoder I need the output values to be the same as input . In other words , I am using a Standar... | How to scale target values of a Keras autoencoder model using a sklearn pipeline ? |
Python : QuestionHow to shade or colorize the background of a seaborn plot using a column of a dataframe ? Code snippetWhich produced this graph : Desired outputWhat I 'd like to have , according to the value in the new column 'background ' and any palette or user defined colors , something like this : <code> import nu... | Colorize the background of a seaborn plot using a column in dataframe |
Python : It is a little weird to me that the refs number in the interactive environment increases 2 after a new object is defined . I created only one object , is n't it ? <code> > > > vTraceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > NameError : name ' v ' is not defined [ 41830 refs... | Why does refs increase 2 for every new object in Python ? |
Python : For a given 2D matrix np.array ( [ [ 1,3,1 ] , [ 2,0,5 ] ] ) if one needs to calculate the max of each row in a matrix excluding its own column , with expected example return np.array ( [ [ 3,1,3 ] , [ 5,5,2 ] ] ) , what would be the most efficient way to do so ? Currently I implemented it with a loop to exclu... | What 's a more efficient way to calculate the max of each row in a matrix excluding its own column ? |
Python : Possible Duplicate : Multiprocessing launching too many instances of Python VM I am trying python 2.6 multiprocessing module with this simple code snippet.But this code cause my OS stopped responding . It looks like the CPU is too busy.What 's wrong with my code ? BTW : it seems that multiprocessing module is ... | Why python multiprocessing module cause CPU completely run out ? |
Python : I 'm trying to train a multi-layered ANN with pylearn2 , using pre-training with RBM . I 've slightly modified the script called run_deep_trainer that is contained in pylearn2\pylearn2\scripts\tutorials\deep_trainer . I want a 4-layered net , where the first 3 are made with 500 GaussianBinaryRBM and the last o... | Pre-training ANN with RBM in pylearn2 |
Python : I recently updated Python 's Numpy package on one of my machines , and apparently I 've been relying on a deprecated feature of numpy for a while now : One of the commenters in the above link pointed out : Probably means you did n't see the deprecation warnings since forever ; ) ... which is correct , I didn't... | Why am I not seeing Numpy 's DeprecationWarning ? |
Python : The public documentation for pandas.io.formats.style.Styler.format says subset : IndexSlice An argument to DataFrame.loc that restricts which elements formatter is applied to.But looking at the code , that 's not quite true ... what is this _non_reducing_slice stuff ? Use case : I want to format a particular r... | What does the subset argument do in pandas.io.formats.style.Styler.format ? |
Python : I have measured the positions of different products in different angles positions ( 6 values in steps of 60 deg . over a complete rotation ) . Instead of representing my values on a Cartesian graph where 0 and 360 are the same point , I want to use a polar graph.With matplotlib , I got a spider chart type grap... | Custom Spider chart -- > Display curves instead of lines between point on a polar plot in matplotlib |
Python : In relation to the previous post on stackoverflowModel ( ) got multiple values for argument 'nr_class ' - SpaCy multi-classification model ( BERT integration ) in which my problem partialy have beed resolved I wanted to share the issue which comes up after implementing the solution.if I take out the nr_class a... | SpaCy - ValueError : operands could not be broadcast together with shapes ( 1,2 ) ( 1,5 ) |
Python : You can use function annotations in python 3 to indicate the types of the parameters and return value , like so : But what if you were writing a function that expects a function as a parameter , or returns one ? I realize that you can write any valid expression in for the annotations , so I could write `` func... | How to indicate that a function expects a function as a parameter , or returns a function , via function annotations ? |
Python : I 'm trying to split a column using regex , but ca n't seem to get the split correctly . I 'm trying to take all the trailing CAPS and move them into a separate column . So I 'm getting all the CAPS that are either 2-4 CAPS in a row . However , it 's only leaving the 'Name ' column while the 'Team ' column is ... | How can I split columns with regex to move trailing CAPS into a separate column ? |
Python : I am writing a simple program to replace the repeating characters in a string with an * ( asterisk ) . But the thing here is I can print the 1st occurrence of a repeating character in a string , but not the other occurrences . For example , if my input is Google , my output should be Go**le.I am able to replac... | Error while Trying To Print the First Occurrence of a repeating Character in a String using Python 3.6 |
Python : I am working on some FASTA-like sequences ( not FASTA , but something I have defined that 's similar for some culled PDB from the PISCES server ) .I have a question . I have a small no of sequences called nCatSeq , for which there are MULTIPLE nBasinSeq . I go through a large PDB file and I want to extract for... | Nested dictionary |
Python : So I have a df like thisI want to sort it in such an alternating way that within a group , say group `` A '' , the first row should have its highest performing person ( in this case `` Chad Webster '' ) and then in the second row the least performing ( which is `` Sheldon Webb '' ) .The output I am looking for... | How to sort a group in a way that I get the largest number in the first row and smallest in the second and the second largest in the third and so on |
Python : Everywhere I search , they say python dictionary 's does n't have any order.When I run code 1 each time shows a different output ( random order ) . But when I run code 2 it always shows the same sorted output . Why is the dictionary ordered in the second snippet ? Outputscode 1 : code 1 again : code 2 ( always... | Dictionary order in python |
Python : I have a repeating fringe pattern on my data and I am trying to get it out by Fourier transforming it and deleting the pattern . However I ca n't seem to find the correct way back to image space . taper is just an array that smooths the edges to get rid of the edge effects while doing an FFT . Then I FFT the a... | Fourier filtering , going back to an image |
Python : Is it possible to show the error bars in the legend ? ( Like i draw in red ) They do not necessarily have to be the correct length , it is enough for me if they are indicated and recognizable.My working sample : I tried a few ways , no one works.With Patch in legend_elements i get no lines for the errorbars , ... | Errorbar in Legend - Pandas Bar Plot |
Python : Example from PEP 484 -- Type HintsRight way to call the function with strIf I call it with int : Call with listEverything works fine right ? greeting function always accepts str as a parameter.But if I try to test function return type , for example , use the same function but change return type to int.Function... | Why return type is not checked in python3 ? |
Python : I wrote this rather poor Python function for prime factorization : and it worked as expected , now I was interested in whether the performance could be better when using an iterative approach : But what I observed ( while the functions gave the same results ) was that the iterative function took longer to run ... | Surprised about good recursion performance in python |
Python : I saw some commits in a Python code base removing `` hourglass imports . '' I 've never seen this term before and I ca n't find anything about it via the Python documentation or web search.What are hourglass imports and when would one use or not use them ? My best guess is that removing them makes submodules e... | What are hourglass imports and why would they be avoided in a codebase ? |
Python : When I do : I receive an output of : It 's not only that some of my keys are deleted but also the value it was holding changed . Why is True given priority over another bool keys ? <code> > > > d= { True : 'yes',1 : 'no',1.0 : 'maybe ' } > > > d > > > { True : 'maybe ' } | Python dictionary breaking the laws of python |
Python : I have a list of tuples I am trying to sort and could use some help . The field I want to sort by in the tuples looks like `` XXX_YYY '' . First , I want to group the XXX values in reverse order , and then , within those groups , I want to place the YYY values in normal sort order . ( NOTE : I am just as happy... | Help sorting : first by this , and then by that |
Python : I would like to see the definition of the class list_iterator . When I try to display its definition with the function help I get an error . Is there a module that I have to import in order to access to its help ? More precisely , I would to know how to get a reference to the object iterable that the iterator ... | Where is the class list_iterator defined ? |
Python : I am trying to understand how static methods work internally . I know how to use @ staticmethod decorator but I will be avoiding its use in this post in order to dive deeper into how static methods work and ask my questions.From what I know about Python , if there is a class A , then calling A.foo ( ) calls fo... | What magic does staticmethod ( ) do , so that the static method is always called without the instance parameter ? |
Python : Here is what I want to do : Is there a way that I can make the order of elements in a pair irrelevant so when O do the membership testing : Any Idea will be greatly appreciated ! Thanks in Advance ! <code> m1 = ( a , b ) m2 = ( c , d ) bad_combos = set ( ) bad_combos.add ( ( m1 , m2 ) ) # ( ( a , b ) , ( c , d... | Membership testing on set of pairs , how do i make the order of element in pairs irrelevant ? |
Python : We 've made a library which uses massively ( with inheritance ) numpy 's MaskedArrays . But I want to run sphinx 's make doctest without testing the inherited methods from numpy , because they make round about 100 failures.This lookls like this : And now that our library also supports numpy 's functions , ther... | prevent sphinx from executing inherited doctests |
Python : Here are a couple of examples taken from django-basic-apps : What 's the point of this string formatting ? <code> # self.title is a unicode string alreadydef __unicode__ ( self ) : return u ' % s ' % self.title # ' q ' is a stringsearch_term = ' % s ' % request.GET [ ' q ' ] | ' % s ' % 'somestring ' |
Python : functools.singledispatch helps to define a single-dispatch generic method . Meanwhile , there is super ( ) for calling methods or accessing attributes of a superclass.Is there something like super ( ) that can be used with singledispatch ? I tried the following , but the result of super ( Derived , value ) is ... | Equivalent to super ( ) for functools.singledispatch |
Python : I have the following two functions : andHowever , when I run both , I find that their results slightly differ : I get : which is very small , but in my case , affects the simulation . If I remove the np.sin from the functions , the difference disappears . Alternatively the difference also goes away if use np.f... | Different result with vectorized code to standard loop in numpy |
Python : I have a first version of legend in the following plot : with the following code : As you can see , I put a title ( k_max = 0.3 and k_max = 1.0 ) for each column of markers and columns.Now , to avoid this redundancy , I am trying to merge all duplicated labels while keeping the title for each marker by doing :... | Matplotlib : How to set a title above each marker which represents a same label |
Python : Many online python examples show interactive python sessions with normal leading `` > > > '' and `` ... '' characters before each line.Often , there 's no way to copy this code without also getting these prefixes.In these cases , if I want to re-paste this code into my own python interpreter after copying , I ... | python : ignoring leading `` > > > '' and `` ... '' in interactive mode ? |
Python : How can I cycle through a , b , c by calling change_x ( ) indefinitely ? Output should be : <code> a = 1b = 2c = 3x = adef change_x ( ) : x = next ? ? print ( `` x : '' , x ) for i in range ( 10 ) : change_x ( ) x : 2x : 3x : 1x : 2 ... | Cycle over list indefinitely |
Python : I 'm trying to parse a logfile of our manufacturing process . Most of the time the process is run automatically but occasionally , the engineer needs to switch into manual mode to make some changes and then switches back to automatic control by the reactor software . When set to manual mode the logfile records... | Finding contiguous , non-unique slices in Pandas series without iterating |
Python : I tested this : With the following partial output : There are two calls for read syscall with different number of requested bytes.When I repeat the same using dd command , just one read syscall is triggered using the exact number of bytes requested.I have googled this without any possible explanation . Is this... | Why Python splits read function into multiple syscalls ? |
Python : I am solving the analytic intersection of 2 cubic curves , whose parameters are defined in two separate functions in the below code.By plotting the curves , it can be easily seen that there is an intersection : zoomed version : However , the sym.solve is not finding the intersection , i.e . when asking for pri... | Analytic intersection between two cubic expressions |
Python : Long story short ... what happens when all references to a threading.Thread object are lost , such as in this function : It kinda looks like the thread keeps going , but it is behaving oddly and I wondered if there might be odd things happening because the garbage collector improperly deleted it or something.O... | What happens when you lose all references to a Python thread ? |
Python : This works but is unwieldy and not very 'Pythonic ' . I 'd also like to be able to run through different values for 'numValues ' , say 4 to 40 ... <code> innerList = [ ] outerList = [ ] numValues = 12loopIter = 0for i in range ( numValues ) : innerList.append ( 0 ) for i in range ( numValues ) : copyInnerList ... | How to create a list of lists where each sub-list 'increments ' as follows : [ 1 , 0 , 0 ] , [ 1 , 1 , 0 ] , [ 1 , 1 , 1 ] |
Python : I have been operating under the theory that generator expressions tend to be more efficient than normal loops . But then I ran into the following example : write a function which given a number , N , and some factors , ps , returns the sum of all the numbers under N that are a multiple of at least one factor.H... | Why is this generator expression function slower than the loop version ? |
Python : Consider the following example codeCreating the object within the loop was intended to assure that the destructor of A would be called before the new A object would be created . But apparently the following happens : Initializing object 1Initializing object 2Deleting object 1Deleting object 2Why is the destruc... | On second initialization of an object , why is __init__ called before __del__ ? |
Python : A user shared with me a link ( shared with just me ... ... ... llama @ bowlcut.com ) . I try to copy the file but I get an error `` File not found '' .If the user changes the share policy to share with everyone & creates a link ( the file number does n't change ) and I rerun it then I am able to copy it . Why ... | Ca n't copy a file shared only with me |
Python : I need to store a large list of numbers in memory . I will then need to check for membership . Arrays are better than lists for memory efficiency . Sets are better than lists for membership checking . I need both ! So my questions are:1 ) How much more memory efficient are arrays than sets ? ( For the converse... | Python sets versus arrays |
Python : I am trying to unpack android 11 image / get info from the raw .img for selinux info , symlinks etc.I am using this wonderful tool : https : //github.com/cubinator/ext4/blob/master/ext4.py35.pyand my code looks like this : then I just have to do ./read.py vendor.img and it works.Untill recently I tried this we... | python - read file info , permissions from raw ext4 image |
Python : I want to create a 2d numpy array where every element is a tuple of its indices.Example ( 4x5 ) : I would create an python list with the following list comprehension : Is there a faster way to achieve the same , maybe with numpy methods ? <code> array ( [ [ [ 0 , 0 ] , [ 0 , 1 ] , [ 0 , 2 ] , [ 0 , 3 ] , [ 0 ,... | Create an array where each element stores its indices |
Python : I have a pandas dataframe that I am reading from a defaultdict in Python , but some of the columns have different lengths . Here is what the data might look like : And I am able to pad the blanks with NaNs like so : Which gives : However , what I 'm really looking for is a way to prepend NaNs instead of append... | Prepending instead of appending NaNs in pandas using from_dict |
Python : I would appreciate if somebody could help me with this ( and explaining what 's going on ) .This works : But this does not : The behaviour I would like to replicate is : Note that what above also work with mutable objects : Of course , knowing that : I tried ( and failed ) : <code> > > > from numpy import arra... | Numpy : need a hand in understanding what happens with the `` in '' operator |
Python : Following sample is taken from `` Dive into python '' book.This sample shows documenting the MP3FileInfo , but how can I add help to MP3FileInfo . tagDataMap <code> class MP3FileInfo ( FileInfo ) : `` store ID3v1.0 MP3 tags '' tagDataMap = ... | Documenting class attribute |
Python : I am working on finding some sort of moving average in a dataframe . The formula will change based on the number of the row it is being computed for . The actual scenario is where I need to compute column Z.Edit-2 : Below is the actual data I am working withThe code snippet I am using is as below : Below is th... | Need to apply different formulas based on the row number in the dataframe |
Python : I want to find a fast way ( without for loop ) in Python to assign reoccuring indices of an array.This is the desired result using a for loop : When I try to add x to a at the indices Px , Py I obviously do not get the same result ( 3.3 vs. 3.1 ) : Is there a way to do this with numpy ? Thanks . <code> import ... | Assigning identical array indices at once in Python/Numpy |
Python : Let 's say I haveI getWhat I would now like to have are functions between all the orange dots , so something likeThereby , fi should be chosen in a way that it reproduces the shape of the spline fit.I found the post here , but the spline produced there seems incorrect for the example above and it 's also not e... | How to convert a spline fit into a piecewise function ? |
Python : I am trying to retrieve the answer for multiplying two int arrays ( output is also an int array ) .For example , num1 = [ 2 , 2 , 0 ] , num2 = [ 1 , 0 ] will give us [ 2 , 2 , 0 , 0 ] What I tried was trying to imitate the grade-school multiplication.However , in the official answer to this question , it adds ... | multiplying two int arrays in python |
Python : My dataframe looks like this : Output : A new 'cluster ' occurs after a 0 shows up in the df . I want to give each of these clusters an unique value , like this : I have tried using enumerate and itertools but since I am new to Python I am struggling with the correct usage and syntax of these options . <code> ... | How to assign unique values to groups of rows in a pandas dataframe based on a condition ? |
Python : I am brand new to python frame introspection and I am trying to set a profiler or a tracer in order to keep track of str function calls . I have setup tracers in various ways but think I am missing some key understandings around frame introspection and how to get builtin function names ( ie str ) When I run te... | Python Observing ` str ` calls by through sys.setprofile and frame inspection |
Python : I am trying to make a tic tak toe game with pygame and I was wondering how would I do the logic here is what I have so far . VIDEO < I only have it when I click on the middle button it will display the player 2 x on the screen and then the image that is hovering over my mouse will turn into O for player 1 turn... | Pygame Tic Tak Toe Logic ? How Would I Do It |
Python : I would like my dice values not to repeat because when it does , it registers a wrong input in my program ( not a crash , simply a string message stating `` Your input was wrong '' ) . It is a board game so I do not want the same values to repeat , for example 6,0 to repeat twice or even thrice . Is there a wa... | Make dice values NOT repeat in if statement |
Python : I was solving this leetcode permutation problem and came across an error that am getting n empty lists inside my returned list which suppose to print different permutations of the given listgetting output = > [ [ ] , [ ] , [ ] , [ ] , [ ] , [ ] ] Expected output= > [ [ 1 , 2 , 3 ] , [ 1 , 3 , 2 ] , [ 2 , 1 , 3... | Permutation Leetcode |
Python : I want to draw a triple bar graph with three different dataframes using matplotLibDF1DF2DF3I am trying to use this piece of code but this is giving error as for this data needs to be from same dataframe <code> index | Number A | 110 B | 22 D | 52 index | NumberA | 100B | 22C | 52 index | Number A | 90 B | 12 C... | How can I draw a bar graph from three different data frames using matplotlib ? |
Python : I 've built a simple scrapy spider running on scrapinghub : The problem I am facing is that the multiple_locs_url response.css returns an empty array despite me seeing it in the markup on the browser side . I checked with scrapy shell and scrapy shell does not see the markup . I guess this is due to the markup... | Scrapy does not fetch markup on response.css |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.