text
stringlengths
46
37.3k
title
stringlengths
12
162
Python : My work : Scan the paperCheck horizontal and vertical lineDetect checkboxHow to know checkbox is ticked or notAt this point , I thought I could find it by using Hierarchical and Contours : Below is my workI got this result ( some high contours , some high hierarchy ) Another result : Low Contours , Low Hierarc...
Best way to detect if checkbox is ticked
Python : I´ve a mind challenge riddle that i want to resolve using python . They give 4 numbers ( 25 , 28 , 38 , 35 ) and they want us to place the numbers in ... + ... - ... = ... One possible solution is 25+38-35=28 . I´ve tried to , making a list from the numbers , iterate them with some loops and an if : lst= [ 25 ...
Python : iterate through a list
Python : How to find only doubles in list ? My version of the algorithmneed find result such as ccode defects : three list ( a , b , c ) , one collections ( dict ) long codeme need leave list doubles values , example . x = [ 1,2,2,2,3,4,5,6,6,7‌​ ] , need [ 2,2,2,6,6 ] not [ 2,6 ] <code> import collectionsa = [ 1,2,3,4...
How to find and leave only doubles in list python ?
Python : Let 's have a.py be : At a console , if I simply import a , things make sense to me : However , if I do the less popular thing and ... I 've read opinions about why people do n't like `` from module import * `` from a namespace perspective , but I ca n't find anything on this behavior , and frankly I figured o...
Why is behavior different with respect to global variables in `` import module '' vs `` from module import * `` ?
Python : Update : This does not hold for R 's inferior ESS process on Mac , but of course I 'm here interested in Python . More updates : It just seems the buffer is slow for evaluating newlines.Whenever I evaluate ( send text ) to the inferior buffer , it is extremely slow to send and render the text in the inferior b...
Slow Mac when sending input to an inferior python process
Python : I have working code that looks like this : I 'd like to know if there is a more elegant way of doing that . I would like to not have my code nested three layers deep like that , and if I could get this to a one-liner likeThat would be even more awesome . I also edited this to point out that the directories are...
pythonic way to access each file in a list of directories
Python : Today while writing some especially terrible code , I stumbled across this mysterious behavior . The Python 3 program below prints a randomly selected attribute of object . How does this happen ? An obvious suspect for the nondeterminism is the random ordering of the vars ( object ) dictionary , but I ca n't s...
Why does this code print a randomly selected attribute ?
Python : We usually use the backslash to escape illegal characters.For example , escaping the double quotes.In f-strings , curly braces are used for placeholding . To represent a curly brace , the braces are doubled.For example , Why was this intuitive approach not favored when developing f-strings ? Is there some tech...
Why are double curly braces used instead of backslash in python f-strings ?
Python : I have just started learning the basics of pandas , and there is one thing which made me think.The output for this program is : One possible solution to get the desired output is to typecast the map object into a list.Output : However if I use range ( ) , which also returns its own type in Python 3 , there is ...
Why is it required to typecast a map into a list to assign it to a pandas series ?
Python : Backgroundmy software visualizes very large datasets , e.g . the data is so large I ca n't store all the data in RAM at any one time it is required to be loaded in a page fashion . I embed matplotlib functionality for displaying and manipulating the plot in the backend of my application.These datasets contains...
Can I make an O ( 1 ) search algorithm using a sorted array with a known step ?
Python : I am trying to do linear combination in Numpy to get the traverse of the vector between two points , but the way I am doing is quite hideous.Output beingIs there any better way to do it ( of course efficiently ) ? <code> import numpy as npa=np.array ( [ 1,2 ] ) b=np.array ( [ 3,4 ] ) t=np.linspace ( 0,1,4 ) c=...
Traversing 2D line in Numpy ?
Python : I 've noticed when experimenting with lists that p= p+i is different then p += i For example : In the above code test prints out to the original value of [ 0 , 1 , 2 , 3 , ] But if I switch p = p + test1 with p += test1 As in the followingtest now equals [ 0 , 1 , 2 , 3 , 8 ] What is the reason for the differe...
difference between adding lists in python with + and +=
Python : I have a list of thousands of elements of a form like the following : I am trying to convert these string elements to tuples using ast.literal_eval , but it is breaking on encountering things like leading zeros ( e.g . in the third tuple string shown ) with the error SyntaxError : invalid token.What would be a...
How can I evaluate a list of strings as a list of tuples in Python ?
Python : Given the classCompilation fails ( using 3.8.0 ) However , according to this post , rotate should be resolvable . Note that qualifying with class name VigenereCipher does n't work either since it ca n't find VigenereCipher ( makes sense , since we are in the process of defining it ) .I can make rotate a module...
How to reference static method from class variable
Python : If I use the debugger , most of the times I just want to see what the interpreter does in my code . I want to step over all code of the framework and libraries I use.AFAIK this is called Black Boxing.How can I do this with Python ipdb or an other Python debugger ? Imagine this : I use a orm framework which I t...
Python Debugger which supports Black Boxing ?
Python : Sometimes , I build up a thing by repeatedly applying map , and then having python perform the operations all at once.For example , I could build up a list of lists of ranges like so : So far , all I have is a single list of 3 items , and a couple of map objects . Laziness achieved . If , at this point , I wou...
Apply python lazy map for in-place functions ?
Python : Is there an easy way to delete a property of a dictionary in Python when it is possible that the property may not be present to begin with ? if the del statement is used , a KeyError is the result : Its a little wordy to use an if statement and you have to type 'foo ' and a twice : Looking for something simila...
Delete a property of a dictionary in Python that may or may not be present
Python : I have a Python script that calls another shell script -When I run the script , arg3 gets split to `` Some '' and `` String '' and is passed as two separate arguments . How can I overcome this to pass `` Some String '' as a single argument ? EDIT : SOLVED I was calling another function internally in the called...
How do I pass parameters with whitespaces to bash through subprocess ?
Python : I looked through Stack Overflow thoroughly and I could n't find any helpful results . At this point I 'm not even sure if this is possible , but because I 'm only a beginner I thought I 'd at least ask it here.Basically , I have multiple data set , each with about 8 million rows and I do not want to loop over ...
Is it possible to do array-wise operation on assignment ?
Python : I am trying to calculate the area of a graph using integrals . The user is supposed to give me 3 numbers : x1 , x2 – the bounds of the integral N is in how many pieces the program will divide the functionHowever , I keep getting wrong results.The first difficulty that I faced is that range accepts only integer...
Errors in program for calculating integrals
Python : I have tried the example provided by official tutorial found here : http : //saratoga.readthedocs.org/en/latest/serviceclasses.htmlI have made a few changes to the code and this is how it looks like : My problem is that I need to provide the account=211829 in the URL just like name=earth.What I have written be...
supplying variables to class dynamically
Python : What 's the most pythonic way to take the single item of a 1-sized list in python ? I usually go forThis would fail for an empty list , but I would like a way to make it fail even if the list is longer , something like : but I find this ugly . Is there anything better ? <code> item = singlet_list [ 0 ] assert ...
Pythonic way to get the single element of a 1-sized list
Python : I am writing my first Python ( 3.4 ) application using SQLalchemy . I have several methods which all have a very similar pattern . They take an optional argument session which defaults to None . If session is passed , the function uses that session , otherwise it opens and uses a new session . For example , co...
Python decorate methods with variable number of positional args and optional arg
Python : The original context of this bug is a piece of code too large to post in a question like this . I had to whittle this code down to a minimal snippet that still exhibits the bug . This is why the code shown below is somewhat bizarre-looking.In the code below , the class Foo may thought of as a convoluted way to...
Annoying generator bug
Python : I 'm fairly new to Python and so I 'm not extremely familiar with the syntax and the way things work exactly . It 's possible I 'm misunderstanding , but from what I can tell from my code this line : is creating 9 references to the same Board object , rather than 9 different Board objects . How do I create 9 d...
List of Lists of Object referencing same object in Python
Python : In Python you can append a list to itself and it will accept the assignment.My question is why ? Python allows this rather than throwing an error , is that because there 's a potential use for it or is it just because it was n't seen as necessary to explicitly forbid this behaviour ? <code> > > > l = [ 0,1 ] >...
What 's the use of a circular reference ?
Python : Here 's my list of tuples : I 'm trying to sum the first index value in a list of tuples where the values at indices 1 and 2 are identical . Note that regions [ 0 ] and regions [ 3 ] have the same values at indices 1 and 2.My desired list is : I realize that I probably need to save it as a dictionary first , p...
Sum tuples if identical values
Python : My code is organized this way : On filters.py there are some exported functions ( included in __init__.py ) and some unexported functions , that begin with underscore.On filters_test.py I have no trouble testing the exported functions , that I can access like this : ( note that `` app '' is part of my PYTHONPA...
testing non-exported methods in python
Python : I have a question about the scope in python functions . I 've included an example that demonstrates the issue I am having . fun0 redefines the first entry in varible c 's list . This change is reflected outside of fun0 , even when I do n't return any values from fun0.fun1 redefines the variable c entirely , bu...
Python function scope
Python : I have a Dataframe like : I want to check when successive Price Values are same then return the row with Max Quantity Value.My Result Dataframe Like : PS : Here in result table Price Value 27850.00 appears once more in Row No:7 and will be considered as independently . Similarly for 28000.00 also . <code> time...
Find Max of successive Similar Values
Python : I am trying to produce string variants by applying substitutions optionally.For example , one substitution scheme is removing any sequence of blank characters.Rather than replacing all occurrences like– I need , instead , two variants to be produced for each occurrence , in that the substitution is performed i...
Combinatorial product of regex substitutions
Python : I 'm having some trouble getting these two dfs to join the way I would like . The first df has a hierarchical index that I created using df1 = df3.groupby ( [ `` STATE_PROV_CODE '' , `` COUNTY '' ] ) .size ( ) to get the count for each county.In SQL I would like to do the following : I would like the result to...
Pandas join on 2 columns
Python : I have a series of lists that looks like this : How can I rearrange the items in each list so that the first item is ' b.something ' ? For the example above : Maintaining the order after the first item is n't important . Thanks for the help . <code> li1 = [ ' a.1 ' , ' b.9 ' , ' c.8 ' , 'd.1 ' , ' e.2 ' ] li2 ...
What is the best way to sort list with custom sorting parameters in Python ?
Python : Is there a simple way to `` simulate '' the assignment of arguments to function parameters ? Say I have a functionand I call it the following way : I want to extract what args and kwargs will be in the function fn , without calling fn.Basically , I am trying to write a function that takes as input a function a...
Simulate the assignment of function arguments to *args and **kwargs
Python : I 'm using portable python 2.7.5.1.The following line : Causes a memory error ( with no other messages ) : Note : there are only comments in lines 1-11.Decreasing one unit in the funny number above the error disappears.Considering that 11 million ai n't that large , I believe there must be some simple setting ...
Memory error allocating list of 11,464,882 empty dicts
Python : I 'm having a strange behaviour here : I just upgraded to Django 1.9.4 from Django 1.9a1 using pip . The installation went fine and Django was running smoothly , but during start up , it still showed the version number `` 1.9a1 '' . Just to make sure I uninstalled Django again using pip and confirmed that my d...
Django 1.9a1 __init__.py is visible in eclipse/PyDev even though it should be deleted ( Windows )
Python : I can not get two coroutines to execute in parallel in my Python 3.6 program . Here is an example : As you can see , the first coroutine gets executed first but the second does not run concurrently.Can you please give me a hint as to how to run them both simultaneously ? Thanks kindly in advance for your help ...
How to execute 2 coroutines in Python 3.6
Python : I am looking for a python library / algorithm / paper to extract a list of groceries out of free text.For example : `` One salad and two beers '' Should be converted to : <code> { 'salad':1 , 'beer ' : 2 }
Extract grocery list out of free text
Python : After an hour search , I have found no answer . My Mac came with Python 2.7 , but I have decided to upgrade to python 3.4 . I installed python 3.4 from python.org.I can now use python 3.4 from terminal . Pip still tries to download python 2.7 packages - numpy for 2.7 is `` up to date '' . When I try to -- upgr...
How can I let pip know that I am interested in packages for python 3.4 ?
Python : I 'm new to Python and there 's something that 's been bothering me for quite some time . I read in `` Learning Python '' by Mark Lutz that when we use a from statement to import a name present in a module , it first imports the module , then assigns a new name to it ( i.e . the name of the function , class , ...
Some confusion regarding imports in Python
Python : In python I have the following : this is a structure to represent a graph and that I find nice because its structure is the same as the one of one of it 's nodes so I can use it directly to initiate a search ( as in depth-first ) . The printed version of it is : And it can be used like : Now , I 'm curious to ...
Creating in c # , c++ and java a strong typed version of a python weak typed structure
Python : Starting with this sample data ... Starting point : Goal output : I am trying to tie all active nid 's to the associated person_id This will then be joined to another dataframe based on the latest date less than a dated activity column . And finally this will be part of the input into a predictive model.Doing ...
Effective-Date-Range One-Hot-Encode groupby
Python : I 'm trying to parse rows from a HTML table with cells containing specific values with regular expressions in Python . My aim in this ( contrived ) example is to get the rows with `` cow '' . My output is < tr class= '' someClass '' > < td > < /td > < td > chicken < /td > < /tr > < tr class= '' someClass '' > ...
Complex non-greedy matching with regular expressions
Python : I want to have this structure for my project : The application is run from project/project.py . However , I constantly get import errors when using relative or absolute imports.Both engines need to import from project.core.base , the utils need to import from project.core.base as well , and project.py ( the ma...
Python imports structure
Python : My program generates the following list ( excerpt ) : It is already sorted by the value of the ' x'-key . I am trying to write a method , that returns a tuple of two elements of this list for a given coordinate ( xPos , yPos ) : The nearest element to the left ( x < = xPos ) The nearest element to the right ( ...
Get closest element from list of dictionaries
Python : I 'm creating a gauge using matplotlib pie as the foundation : Now the problem is my gauge arrow ( in red ) seems to get cut off at the top if it is sitting between 2 and 4 . Almost as if there is an imaginary line between the left corner of the 2 wedge and the right corner of the 4 wedge . As you can see with...
Strange pie graph cut off
Python : In the section on Custom Classes of The Python Language Reference it is stated that : Special attributes : __name__ is the class name ; __module__ is the module name in which the class was defined ; __dict__ is the dictionary containing the class ’ s namespace ; __bases__ is a tuple ( possibly empty or a singl...
Custom classes with empty __bases__ attribute
Python : I have a python modules written in C , it has a main module and a submodule ( name with a dot , not sure this can be called real submodule ) : The module is compiled as sysipc.so , and when I put it in current directory , following import works without problem : The problem is I want to put this module inside ...
python import path for sub modules if put in namespace package
Python : When piping printed output from a python script to a command like grep , the output from the script seems to only be piped to the follow-up command after completion of the entire script.For example , in a script test_grep.py like the following : when called with ./test_grep.py | grep message , nothing will app...
Is there any way to have output piped line-by-line from a currently executing python program ?
Python : Say I have the following DataFrame which has a 0/1 entry depending on whether something happened/did n't happen within a certain month.What I want is to create a 2nd column that lists the # of months until the next occurrence of a 1 . That is , I need : What I 've tried : I have n't gotten far , but I 'm able ...
Pandas : fill one column with count of # of obs between occurrences in a 2nd column
Python : I need help in the most efficient way to convert the following list into a dictionary : At present , I do the following : However , I believe there should be a more efficient way to achieve the same . Any idea ? <code> l = [ ' A:1 ' , ' B:2 ' , ' C:3 ' , 'D:4 ' ] mydict = { } for e in l : k , v = e.split ( ' :...
Efficient way to convert a list to dictionary
Python : Suppose we 've got an array of intervals [ ( a1 , b1 ) , ( a2 , b2 ) , ... , ( an , bn ) ] sorted with respect to starting positions and length . We want to unite all intersecting intervals . Here is a small sample data set that contains at least 2 isolated groups of intervals : And a couple of functions we ne...
Rewrite an interval union algorithm functionally
Python : Suppose I had a class A : And I defined a factory method called factory : Now , If I do print ( type ( A ( 1 , 2 ) ) ) and print ( type ( factory ( 1 , 2 ) ) ) they will show that these are different types . And if I try to do factory ( 1 , 2 ) .sum ( ) I 'll get an exception . But , type ( A ) .__name__ and t...
How to `` fool '' duck typing in Python
Python : Let 's say we have a complex API function , imported from some library.I want to write a simple wrapper around that function to make a tiny change . For example , it should be possible to pass the first argument as a string . How to document this ? I considered the following options : Option 1 : Disadvantage :...
How to document small changes to complex API functions ?
Python : I was experimenting in the python shell with the type ( ) operator . I noted that : returns an error which is trouble scanning the stringyet : works fine and responds that a string was found.What is going on ? does it have to do with the fact that type ( `` '' string `` '' ) is interpreted as type ( `` '' `` '...
So what is the story with 4 quotes ?
Python : How do I sum the values of list to the power of their indices in Python 3 ? Example : The idea is to create a unique index for any possible combination of non-negative numbers in the list . This way , I can use the list to compute an index of something.Edit : while the question has been answered , I just reali...
How to sum the values of list to the power of their indices
Python : Here is a example of a cyclic reference of Python . after this , Why do a and b have a reference count of 3 ? ? Sorry guys i just took a mistake . the real question is the different one.Why is the reference count of 'GNU ' is 4 ? Thanks in advance : ) <code> > > > a = [ 1 ] > > > b = [ 2 ] > > > a.append ( b )...
In Python , what is the reference count of cyclic reference and why ?
Python : The excel is like the left picture with 3 columns.When inserting into database , I need to add 2 columns more manually like right picture showed and insert altogether 5 columns in database finally . These 2 additional columns information is fetched from other databases.And another function is if there is alrea...
django1.8- how to append information manually when uploading Excel and inserting into database
Python : I started learning about multiprocessing in python and I noticed that same code is executed much faster on main process than in process which is created with multiprocessing module.Here is simplified example of my code , where i first execute code on main process and print time for first 10 calculation and tim...
Executing python code in new process is much slower than on main process
Python : I just discovered that the various itertools functions return class types which are not considered generators by the Python type system.First , the setup : Then : The glob.iglob ( ) result , or any other typical generator , is of type types.GeneratorType . But itertools results are not . This leads to a great ...
Why are Python itertools not classified as generators ( GeneratorType ) ?
Python : My question is exactly the same as this question . I have the array ( list ) of characters . I would like to get all possible sequence combinations from that list but with the limit of characters ( for example : 2 characters as maximum ) . Further , no single character can be repeated in a permutation line : I...
Python : Produce all possible sequence combination from a list with character limit
Python : I 'm trying to serialise Python functions ( code + closures ) , and reinstate them later on . I 'm using the code at the bottom of this post.This is very flexible code . It allows the serialisation and deserialisation of inner functions , and functions that are closures , such as those that need their context ...
Can I restore a function whose closure contains cycles in Python ?
Python : I have some strings in a text file that I want to process . I tried many regex patterns but none of them are working for me.I need the following string combinations : <code> someone can tell/figurea/the squeaky wheel gets the grease/oilaccounts for ( someone or something ) that's/there 's ( something/someone )...
How to split string at specific character and build different string combinations
Python : I 've a dataframe with list of items separated by , commas as below.Also I 've 3 list of arrays which has all items said above clubbed into specific groups as belowX = [ X1 , X2 , X3 , X4 , X5 ] Y = [ Y1 , Y2 , Y3 , Y4 , Y5 ] Z = [ Z1 , Z2 , Z3 , Z4 , Z5 ] my task is to split the each value in the dataframe & ...
Looping through multiple arrays & concatenating values in pandas
Python : I am not able to figure out what is happening here . Appending reference to range function is kind of creating a recursive list at index 3 . Whereas , when I try this : I can easily deduce the reason for the second case but not able to understand what appending reference to range function is doing to the list ...
What range function does to a Python list ?
Python : I was trying to do this in Python 3.5.2 : but got the unexpected result : 20422138979591827456It 's working fine in Python 2.7.12 , result is : 20422138979591829126LAny idea why Python 3 gave me the wrong result ? <code> int ( 204221389795918291262976/10000 )
Strange error in python3 when doing big int calculation
Python : I 'm working on Windows . I 've a Python file to create a new CSV file and I view that using notepad ( even through Ms Excel ) .The resulted file in notepad : My doubt here is whether the carriage return \r works or not ? ? ? It works like lineterminator= '' in notepad . But in excel , it works like '\n'The ou...
'\r ' not working as ` lineterminator ` within Python ` csv.writer ( ) `
Python : I have two numpy arrays : One array x with shape ( n , a0 , a1 , ... ) and one array k with shape ( n , b0 , b1 , ... ) . I would like to compute and array of exponentials such that the output has dimension ( a0 , a1 , ... , b0 , b1 , ... ) and If there is only one a_i and one b_j , broadcasting does the trick...
Compute x**k with x , k being arrays of arbitrary dimensionality
Python : I would like to compare elements in a dictionary to one another , and remove items according to some comparison criteria . And I 'd love it to be efficient . I have a function that can do this , but it repeatedly copies the dictionay . Surely there is a superior way : <code> mydict = { 1:5,2:7,3:9,4:9,7:7,8:0,...
Compare a dict to itself and remove similar keys efficiently
Python : I need to iterate a tree/graph and produce a certain output but following some rules : The expected output should be ( order irrelevant ) : The rules are : The top of the tree 'bde ' ( leftmost_root_children+root+rightmost_root_children ) should always be presentThe left-right order should be preserved so for ...
How to iterate this tree/graph
Python : I 'm currently trying to make a sort of `` word mixer '' : for two given words and the desired length specified , the program should return the `` mix '' of the two words . However , it can be any sort of mix : it can be the first half of the first word combined with the second half of the second word , it can...
Contract words in python with set length
Python : Recently I 've been doing things like this : as opposed to something like this : The question is n't specific to Tkinter , but it 's a good example . The function f is only used as the callback for the button , so I 've chosen to define it inside __init__ . That way , only code inside __init__ even knows about...
Code style - 'hiding ' functions inside other functions
Python : Let 's say I have a list of values , I also have a pandas dataframe of the form , df : The rows are a subset of all pairwise combinations in lst . Note that every combination appears at most once.What I want is a new dataframe where the remaining combinations are filled in with a value of 0.For example , new_d...
How to efficiently fill an incomplete pandas dataframe consisting of pairwise combinations of values in a list ?
Python : I 'm working with a query that looks like so : Given the filters Q query , can I pop one of the queries ? I 'd like to remove the Q ( mailbagstats__num_letters2__gt= int ( cut ) ) query from this Q query for a new filter down the line.Normally , I use lists and reduce but this one is constructed via Q ( ) & Q ...
Popping a query from django Q query ?
Python : In PEP 366 - Main module explicit relative imports which introduced the module-scope variable __package__ to allow explicit relative imports in submodules , there is the following excerpt : When the main module is specified by its filename , then the__package__ attribute will be set to None . To allow relative...
What is the correct boilerplate for explicit relative imports in Python ?
Python : I 've encountered two versions of code that both can accomplish the same task with a little difference in the code itself : andMy question is , is the file object f a list by default just like data ? If not , why does the first chunk of code work ? Which version is the better practice ? <code> with open ( `` f...
Is an object file a list by default ?
Python : I feel like Python ought to have a built-in to do this . Take a list of items and turn them into a dictionary mapping keys to a list of items with that key in common.It 's easy enough to do : But this is frequent enough of a use case that a built-in function would be nice . I could implement it myself , as suc...
Grouping items by a key ?
Python : I 'm new to tensorflow 2.0 , and have n't done much except designing and training some artificial neural networks from boilerplate code . I 'm trying to solve an exercise for newcomers into the new tensorflow . I created some code , but it does n't work . Below is the problem definition : Assuming we have tens...
Increasing each element of a tensor by the predecessor in Tensorflow 2.0
Python : I have a dataframe : On 'col2 ' I want to keep only the first 1 from the top and replace every 1 below the first one with a 0 , such that the output is : Thank you very much . <code> col1 col2 a 0 b 1 c 1 d 0 c 1 d 0 col1 col2 a 0 b 1 c 0 d 0 c 0 d 0
Pandas dataframe : Remove secondary upcoming same value
Python : With a data like this one ( but with 40e3 columns ) I look for a vectorized way to put the boolean and in a result Series : For now I only get an ugly solution with a for loop : :with the B.M . answer I get thisWe can probably avoid this new for loop . <code> import pandas as pdtcd = pd.DataFrame ( { ' a ' : {...
Vectorized `` and '' for pandas columns
Python : I have the following string interpolation : It obviously fails because format is literally trying to access the object test1 and its attribute 1 . Is there a way to format this string and force the key values to be taken as strings ? ( Looking for a Python 2 and 3 solution . ) <code> > > > a = { 'test1.1 ' : 5...
Forcing dict keys to be used as argument specifiers with str.format
Python : I am trying to group based on their sequence relationship beween the two columns . I am expecting the result something below : To make it more clear : - df1 and df2 have a relationship based on their sequence . For example , 10 has a direct relation with 20 and 10 has an indirect relation with 30 through 20 . ...
How do I group dataframe columns based on their sequence relation
Python : I had a bug that I reduced down to this : Which outputs this : What 's going on here ? <code> a = [ ' a ' , ' b ' , ' c ' ] print ( `` Before '' , a ) '' `` .join ( a ) print ( `` After '' , a ) runfile ( ' C : /program.py ' , wdir=r ' C : / ' ) Before [ ' a ' , ' b ' , ' c ' ] After [ ' a ' , ' b ' , ' c ' ]
Why is the join built-in having no influence on my code ?
Python : How can I add keys to a dict within a list , if the dict contains a certain key , from values in another list ? I have a list of dicts . Those dicts either contain only one key ( 'review ' ) , or two keys ( 'review ' and 'response ' ) . When the dict contains the key 'response ' , I want to add two keys , with...
Adding keys to dicts within a list , from values in a list
Python : I 'm confused about the role played by the backend used by matplotlib in determining what formats can be rendered.For example , the documentation says that the 'agg ' backend generates PNG , `` raster graphics '' but if I I can useto generate a PDF , or to produce vector graphics.What role does the backend pla...
What limits does the matplotlib backend place on rendering formats ?
Python : So I have a tensorflow model in python 3.5 registered with the ML engine and I want to run a batch prediction job using it . My API request body looks like : Then the batch prediction job runs and returns `` Job completed successfully . `` , however , it was completely unsuccessful and consistently threw the f...
ML Engine Batch Prediction running on wrong python version
Python : I have implemented a method for bulk loading a point quadtree . But for some inputs it does n't work correctly , for example if there are many points that have the same x- or y-coordinate.An example dataset would be : The problem occurs at the points : ( 11,4 ) , ( 11,5 ) , ( 11,15 ) and ( 5,10 ) , ( 5,4 ) .Th...
Bulk loading point quadtree
Python : I made a mistake in my question here ( wrong requested input and expected output ) : Comparing dicts , updating NOT overwriting valuesI am not looking for this solution : Combining 2 dictionaries with common keySo this question is not a duplicateProblem statement : requested input : expected output ( I do n't ...
Compare dicts and merge them . No overwrite and no duplicate values
Python : I need to know start and end indexes of matches from next regular expression : Example string is s='GATGDTATGDTAAAA'pat.findall ( s ) returns desired matches [ 'ATGDTATGD ' , 'ATGDTAAAA ' ] . How to extract start and end indexes ? I tried : However , it.end ( ) always coincide with it.start ( ) , because the b...
Get start and stop indexes of overlapping matches ?
Python : I was wondering if anyone could tell me why my python code for solving quadratic equations is n't working . I have looked through it and have n't found any errors.When a=1 b=-4 and c=-3 I am expecting -1 and 4 but get 5.5 and 0.5 <code> print ( `` This program will solve quadratic equations for you '' ) print ...
incorrect answers for quadratic equations
Python : Given that , I have a dataframe as below : I wish to have the Maximum and minimum of each row in column B . My favorite output is : What I already tried is the below code which does not work : <code> import pandas as pdimport numpy as npdict = { `` A '' : [ [ 1,2,3,4 ] , [ 3 ] , [ 2,8,4 ] , [ 5,8 ] ] } dt = pd...
How to get maximum and minimum of a list in column ?
Python : I though this would be straightforward , unfortunately , it is not.I am trying to build a function to take an iterable of dictionaries ( i.e. , a list of unique dictionaries ) and return a list of lists of unique groupings of the dictionaries.If I have x players I would like to form k teams of n size.This ques...
All combinations of set of dictionaries into K N-sized groups
Python : I have a result like this : And I 'd like to convert it to unique values like this , in sorted order : And I 'm pretty sure there 's something like a one-liner trick in Python ( batteries included ) but I ca n't find one . <code> [ ( 196 , 128 ) , ( 196 , 128 ) , ( 196 , 128 ) , ( 128 , 196 ) , ( 196 , 128 ) ,...
How to transform a pair of values into a sorted unique array ?
Python : In Python , I have a decorator that has to skip any real work if a function is defined locally in the one that calls it . I made a simple testing script : It prints this : As I see , Python sees that the function is defined in a local space ( < locals > in the printed text ) , but I ca n't see how I can find t...
How to detect if a function has been defined locally ?
Python : I 'm stumped by this seemingly trivial problem ... I would like to use python to take a string of numbers ( `` 123 '' for example ) and create a list that has all possible expressions where a `` + '' or `` - '' ( or nothing at all ) can be inserted between any numbers.For the example `` 123 '' the list would b...
Taking a string of numbers and inserting + and - operators
Python : I tried to scrap yellow pages according to its categories . So i load categories from a text file and feed it to the start_urls . The problem i am facing here is saving the output separately for each category . Following is the code i tried to implement : Opening the file in settings.py and making a list to ac...
Making separate output files for every category in scrapy
Python : I was asked during an interview to implement bisection search to improve search time and I came up with this . I came home and test it but it looks like the linear search is doing way better than my bisection search . Did I do something wrong here ? <code> import timesorted_list = range ( 0 , 10000000 ) needle...
Why my bisection search is slower than linear search in python ?
Python : I 'm writing a set of test cases for users new to Python . One of the problems I 've noticed with my tests is that its possible to get false positives . They may have gotten lucky and happened to give every element in the correct order , however they really should be using a structure that is ordered.So far th...
How can I tell if a structure in Python has order ?
Python : I came up with the following code to decorate instance methods using a decorator that requires the instance itself as an argument : This seems to work great , but I fear that I may have overlooked some unintended side effects of this trick . Am I about to shoot myself in the foot , or is this safe ? Note that ...
Python : Anything wrong with dynamically assigning instance methods as instance attributes
Python : My xml file is encoding thus : I am trying to parse this file using beautiful soup.But this results in packages\bs4__init__.py '' , line 245 , in init markup = markup.read ( ) File `` C : \Users\gregg_000\AppData\Local\Programs\Python\Python36\lib\encodings\cp125 2.py '' , line 23 , in decode return codecs.cha...
handling encoding error with xml with beautiful soup