lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
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 HierarchyHowever...
for i in range ( len ( contours_region ) ) : # I already have X , Y , W , H of the checkbox through # print ( i ) # cv2.connectedComponentsWithStats x = contours_region [ i ] [ 0 ] [ 1 ] # when detecting checkbox x_1 = contours_region [ i ] [ 2 ] [ 1 ] y = contours_region [ i ] [ 0 ] [ 0 ] y_1 = contours_region [ i ] [...
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 , 28 , 38...
for z in lst : for x in lst : for c in lst : for v in lst : if z+x-c==v : print z , x , c , v
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 ]
import collectionsa = [ 1,2,3,4,5,2,4,5 ] b = [ ] for x , y in collections.Counter ( a ) .items ( ) : if y > 1 : b.append ( x ) print ( b ) # [ 2 , 4 , 5 ] c = [ ] for item in a : if item in b : c.append ( item ) print ( c ) # [ 2 , 4 , 5 , 2 , 4 , 5 ]
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 out that t...
def foo ( ) : global spam spam = 42 return 'this ' > > > import a > > > a.foo ( ) 'this ' > > > a.spam42 > > > from a import * > > > foo ( ) 'this ' > > > spamTraceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > NameError : name 'spam ' is not defined > > > a.spamTraceback ( most recent c...
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 buffer . Y...
def uselessfunction ( ) : a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 > > > > > > > > > ... ... ... ... ... ... ... ... > > >
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 not all ...
# Wow . Much nesting . So spacebarif __name__ == '__main__ : for eachDir in list_of_unrelated_directories : for eachFile in os.listdir ( eachDir ) : if eachFile.endswith ( '.json ' ) : # do stuff here for each file that ends with .json in all these directories : # do stuff
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 see how th...
class TypeUnion : passclass t : passdef super_serious ( obj ) : proxy = t ( ) for name , val in vars ( object ) .items ( ) : if not callable ( val ) or type ( val ) is type : continue try : setattr ( t , name , lambda _ , *x , **y : val ) except AttributeError : pass return proxyprint ( super_serious ( TypeUnion ( ) ) ...
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 technical or ...
> > > `` \ '' '' == ' '' 'True > > > f '' { { } } '' == `` { } '' True > > > f'\ { \ } ' File `` < stdin > '' , line 1SyntaxError : f-string expression part can not include a backslash
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 no need t...
import pandas as pddata = pd.DataFrame ( { 'Column1 ' : [ ' A ' , ' B ' , ' C ' ] } ) data [ 'Column2 ' ] = map ( str.lower , data [ 'Column1 ' ] ) print ( data ) Column1 Column2 0 A < map object at 0x00000205D80BCF98 > 1 B < map object at 0x00000205D80BCF98 > 2 C < map object at 0x00000205D80BCF98 > import pandas as p...
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 three in...
732839.154392732839.154392732839.154393732839.154393732839.154394732839.154394732839.154395732839.154396 732839.154396732839.154397732839.154397732839.154398732839.154398732839.154399etc ... grab first and second element of timesubtract second element of time with first , obtain stepsubtract bounding x value with first...
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 ) ?
import numpy as npa=np.array ( [ 1,2 ] ) b=np.array ( [ 3,4 ] ) t=np.linspace ( 0,1,4 ) c= ( np.asarray ( [ t*a [ 0 ] , t*a [ 1 ] ] ) +np.asarray ( [ ( 1-t ) *b [ 0 ] , ( 1-t ) *b [ 1 ] ] ) ) .Tprint c [ [ 3 . 4 . ] [ 2.33333333 3.33333333 ] [ 1.66666667 2.66666667 ] [ 1 . 2 . ] ]
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 different value ...
test = [ 0 , 1 , 2 , 3 , ] p = testtest1 = [ 8 ] p = p + test1print test test = [ 0 , 1 , 2 , 3 , ] p = testtest1 = [ 8 ] p += test1print test
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 good way...
pixels = [ ' ( 112 , 37 , 137 , 255 ) ' , ' ( 129 , 39 , 145 , 255 ) ' , ' ( 125 , 036 , 138 , 255 ) ' ... ] pixels = [ ast.literal_eval ( pixel ) for pixel in pixels ]
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-level me...
from __future__ import annotationsfrom typing import ClassVar , Dict , Finalimport abcclass Cipher ( abc.ABC ) : @ abc.abstractmethod def encrypt ( self , plaintext : str ) - > str : pass @ abc.abstractmethod def decrypt ( self , ciphertext : str ) - > str : passclass VigenereCipher ( Cipher ) : @ staticmethod def rota...
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 trust , an...
cut_hair_method ( orm_object.user )
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 would like t...
foo = [ 256 ] *3foo = map ( range , foo ) foo = map ( list , foo ) foo = [ 256 ] *3foo = map ( range , foo ) foo = map ( list , foo ) in_place_op = map ( lambda x : x.sort ( reverse=True ) , foo ) foo = [ 256 ] *3foo = map ( range , foo ) foo = map ( list , foo ) in_place_op = map ( lambda x : x.sort ( reverse=True ) ,...
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 similar to dict...
a = { } del a [ 'foo ' ] > > > KeyError : 'foo ' a = { } if 'foo ' in a : del a [ 'foo ' ] a = { } a.get ( 'foo ' ) # Returns None , does not raise error
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 script b...
arg1 = `` -a '' arg2 = `` -b '' arg3 = `` Some String '' argList = [ `` script.sh '' , arg1 , arg2 , arg3 ] subprocess.call ( argList )
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 each row ...
> > > import pandas as pd > > > df1 = pd.DataFrame ( [ [ 1,2 ] , [ 3,4 ] , [ 5,6 ] ] ) > > > df1.columns = [ ' A ' , ' B ' ] > > > df1 A B0 1 21 3 42 5 6 > > > df2 = pd.DataFrame ( 0 , index = list ( df1 [ ' B ' ] ) , columns = list ( df1 [ ' A ' ] ) ) > > > df2 1 3 52 0 0 04 0 0 06 0 0 0 > > > listA = list ( df1 [ ' A...
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 integers.Also z=...
# -*- coding : UTF-8 -*-import mathdef f ( x ) : y = ( -1/6.0 ) * ( x-1 ) * ( x-2 ) * ( x+2 ) * ( x-4 ) return y x1=int ( raw_input ( 'Δωστε το χ1 οπου αρχιζει η μετρηση του ολοκληρωματος \n ' ) ) # greek lettersx2=int ( raw_input ( 'Δωστε χ2 οπου θελετε να ολοκληρωνεται η μετρηση \n ' ) ) N=int ( raw_input ( 'Δωστε το...
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 below is wo...
http : //23.21.167.60:8094/v1/yearlength ? name=earth import jsonfrom saratoga.api import SaratogaAPI , DefaultServiceClassclass PlanetServiceClass ( DefaultServiceClass ) : def __init__ ( self , myaccount ) : self.yearLength = { `` earth '' : self.myquery ( myaccount ) , `` pluto '' : { `` seconds '' : 7816176000 } } ...
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 ?
item = singlet_list [ 0 ] assert ( len ( singlet_list ) == 1 ) item = singlet_list [ 0 ]
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 , consider th...
def _stocks ( self , session=None ) : `` '' '' Return a list of all stocks in database . '' '' '' newsession = False if not session : newsession = True session = self.db.Session ( ) stocks = [ stock.ticker for stock in session.query ( Stock ) .all ( ) ] if newsession : session.close ( ) return stocks from functools imp...
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 get some...
class Foo ( object ) : def __init__ ( self , n ) : self.generator = ( x for x in range ( n ) ) def __iter__ ( self ) : for e in self.generator : yield e for c in Foo ( 3 ) : print c # 0 # 1 # 2print list ( Foo ( 3 ) ) # [ 0 , 1 , 2 ] class Bar ( Foo ) : def __len__ ( self ) : return sum ( 1 for _ in self.generator ) fo...
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 different ...
largeBoard = [ [ Board ( ) for i in range ( 3 ) ] for j in range ( 3 ) ] largeBoard = [ [ Board ( ) for i in range ( 3 ) ] for j in range ( 3 ) ] x_or_o = ' x ' largeBoard [ 1 ] [ 0 ] .board [ 0 ] [ 0 ] = ' g ' # each Board has a board inside that is a list for i in range ( 3 ) : for j in range ( 3 ) : for k in range (...
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 ?
> > > l = [ 0,1 ] > > > l.append ( l ) > > > l [ 0 , 1 , [ ... ] ] > > > l [ -1 ] [ 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 , probably w...
regions = [ ( 23.4 , 12 , 12341234 ) , ( 342.23 , 19 , 12341234 ) , ( 4312.3 , 12 , 12551234 ) , ( 234.2 , 12 , 12341234 ) ] result = [ ( 257.6 , 12 , 12341234 ) , ( 342.23 , 19 , 12341234 ) , ( 4312.3 , 12 , 12551234 ) ]
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 PYTHONPATH ) But ...
app/sampling├── __init__.py├── filters.py└── test └── filters_test.py from app.sampling import exported_function from ..filters import _private_function
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 , but the cha...
def fun0 ( a , b , c ) : c [ 0 ] = a [ 0 ] + b [ 0 ] returndef fun1 ( a , b , c ) : c = a [ 0 ] + b [ 0 ] returndef fun2 ( a , b , c ) : c = a + b returndef main ( ) : val1 = [ 'one ' ] val2 = [ 'two ' ] val3 = [ `` ] fun0 ( val1 , val2 , val3 ) print val3 val4 = [ ] fun1 ( val1 , val2 , val4 ) print val4 val5 = 1 val6...
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 .
timestamp Order Price Quantity0 2019-10-09 09:15:42 0 27850.00 20401 2019-10-09 09:15:42 0 27850.00 19802 2019-10-09 09:15:53 0 27860.85 18003 2019-10-09 09:16:54 0 27860.85 23404 2019-10-09 09:18:48 0 27860.85 15005 2019-10-09 09:21:08 0 27979.00 18406 2019-10-09 09:21:08 0 27979.00 20207 2019-10-09 09:21:12 0 27850.0...
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 in one var...
> > > re.sub ( r'\s+ ' , `` , ' a b c ' ) 'abc ' [ ' a b c ' , ' a bc ' , 'ab c ' , 'abc ' ] def vary ( target , pattern , subst ) : occurrences = [ m.span ( ) for m in pattern.finditer ( target ) ] for path in itertools.product ( ( True , False ) , repeat=len ( occurrences ) ) : variant = `` anchor = 0 for ( start , e...
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 be as fo...
STATE_PROV_CODE COUNTY COUNTAL Autauga County 1 Baldwin County 1 Barbour County 1 Bibb County 1 Blount County 1 STATE_PROV_CODE COUNTY ANSI Cl FIPS0 AL Autauga County H1 010011 AL Baldwin County H1 010032 AL Barbour County H1 010053 AL Bibb County H1 010074 AL Blount County H1 01009 SELECT STATE_PROV_CODE , COUNTY , FI...
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 .
li1 = [ ' a.1 ' , ' b.9 ' , ' c.8 ' , 'd.1 ' , ' e.2 ' ] li2 = [ ' a.4 ' , ' b.1 ' , ' c.2 ' , 'd.2 ' , ' e.4 ' ] li1 = [ ' b.9 ' , ' a.1 ' , ' c.8 ' , 'd.1 ' , ' e.2 ' ] li2 = [ ' b.1 ' , ' a.4 ' , ' c.2 ' , 'd.2 ' , ' e.4 ' ]
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 and a list...
def fn ( a , b , c='default ' , *args , **kwargs ) : print ( f ' a= { a } , b= { b } , c= { c } ' ) print ( f'args= { args } ' ) print ( f'kwargs= { kwargs } ' ) > > > args = ( 1 , 2 , 3 , 4 ) > > > kwargs = { 'extra_kw ' : 5 } > > > fn ( *args , **kwargs ) a=1 , b=2 , c=3args= ( 4 , ) kwargs= { 'extra_kw ' : 5 } def e...
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 that can ...
x = [ { } for i in range ( 11464882 ) ] > > > Traceback ( most recent call last ) : File `` < module1 > '' , line 12 , in < module > MemoryError > > >
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 django fol...
from django.core.management import execute_from_command_lineFile `` C : \Program Files ( x86 ) \Python 3.5\lib\site-packages\django\__init__.py '' , line 1 , in < module > from django.utils.version import get_versionImportError : No module named 'django.utils ' from django.utils.version import get_versionVERSION = ( 1 ...
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
import asyncio , timedef main ( ) : loop = asyncio.get_event_loop ( ) loop.run_until_complete ( start_coros ( ) ) async def start_coros ( ) : await coro1 ( ) await coro2 ( ) async def coro1 ( ) : print ( `` coro1 '' ) time.sleep ( 3000 ) async def coro2 ( ) : print ( `` coro2 - we want to get here '' ) if __name__ == `...
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 :
{ '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 -- upgrade a pac...
Requirement already up-to-date : numpy in /Library/Python/2.7/site-packages
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 , etc . pre...
# mod1.pyfrom mod2 import testtest ( 'mod1.py ' ) # mod2.pydef countLines ( name ) : print len ( open ( name ) .readlines ( ) ) def countChars ( name ) : print len ( open ( name ) .read ( ) ) def test ( name ) : print 'loading ... ' countLines ( name ) countChars ( name ) print '-'*10 > > > import mod1loading ... 344 -...
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 know how ...
graph = { } graph [ 1 ] = { } graph [ 2 ] = { } graph [ 3 ] = { } graph [ 1 ] [ 3 ] = graph [ 3 ] graph [ 2 ] [ 1 ] = graph [ 1 ] graph [ 2 ] [ 3 ] = graph [ 3 ] graph [ 3 ] [ 2 ] = graph [ 2 ] { 1 : { 3 : { 2 : { 1 : { ... } , 3 : { ... } } } } , 2 : { 1 : { 3 : { 2 : { ... } } } , 3 : { 2 : { ... } } } , 3 : { 2 : { ...
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 something...
import pandas as pdstart_data = { `` person_id '' : [ 1 , 1 , 1 , 1 , 2 ] , `` nid '' : [ 1 , 2 , 3 , 4 , 1 ] , `` beg '' : [ `` Jan 1 2018 '' , `` Jan 5 2018 '' , `` Jan 10 2018 '' , `` Feb 5 2018 '' , `` Jan 25 2018 '' ] , `` end '' : [ `` Feb 1 2018 '' , `` Mar 4 2018 '' , `` '' , `` Oct 18 2018 '' , `` Nov 10 2018 ...
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 '' > < td > < ...
import reresponse = `` ' < tr class= '' someClass '' > < td > < /td > < td > chicken < /td > < /tr > < tr class= '' someClass '' > < td > < /td > < td > chicken < /td > < /tr > < tr class= '' someClass '' > < td > < /td > < td > cow < /td > < /tr > < tr class= '' someClass '' > < td > < /td > < td > cow < /td > < /tr >...
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 main file r...
requirements.txtREADME.md.gitignoreproject/ __init__.py project.py core/ __init__.py base.py engines/ __init__.py engine1.py engine2.py utils/ __init__.py refine_data.py whatever.py # engines/engine1.pyfrom project.core.base import MyBaseClass ImportError : No module named project.core.base # engines/engine1.pyfrom ..c...
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 ( x > xPos ...
my_list = [ { ' x ' : 1764 , ' y ' : 18320 , 'class ' : 'note ' , 'id ' : 'd1e2443 ' } , { ' x ' : 1764 , ' y ' : 20030 , 'class ' : 'note ' , 'id ' : 'd1e2591 ' } , { ' x ' : 1807 , ' y ' : 12650 , 'class ' : 'note ' , 'id ' : 'd1e1362 ' } , { ' x ' : 2243 , ' y ' : 20120 , 'class ' : 'note ' , 'id ' : 'd1e2609 ' } , ...
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 the blac...
import matplotlib.pyplot as pltimport math theta = 0.2group_size= [ 10,10,10,10,10,50 ] mid = [ 18,54,90,126,162 ] from textwrap import wraplabels= [ ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' , '' ] labels = [ '\n'.join ( wrap ( l , 9 ) ) for l in labels ] fig , ax = plt.subplots ( ) ax.axis ( 'equal ' ) pie3 = ax.pie ( gr...
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 singleton ) co...
> > > object.__bases__ ( )
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 a namespa...
PyMODINIT_FUNC initsysipc ( void ) { PyObject *module = Py_InitModule3 ( `` sysipc '' , ... ) ; ... init_sysipc_light ( ) ; } static PyTypeObject FooType = { ... } ; PyMODINIT_FUNC init_sysipc_light ( void ) { PyObject *module = Py_InitModule3 ( `` sysipc.light '' , ... ) ; ... PyType_Ready ( & FooType ) ; PyModule_Add...
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 appear for 1...
# ! /usr/bin/env pythonfrom time import sleepprint `` message1 '' sleep ( 5 ) print `` message2 '' sleep ( 5 ) print `` message3 '' # ! /usr/bin/env bashecho `` message1 '' sleep 5 echo `` message2 '' sleep 5echo `` message3 ''
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 to fill t...
Y = [ 0,0,1,1,0,0,0,0,1,1,1 ] X = pd.date_range ( start = `` 2010 '' , freq = `` MS '' , periods = len ( Y ) ) df = pd.DataFrame ( { ' R ' : Y } , index = X ) R2010-01-01 02010-02-01 02010-03-01 12010-04-01 12010-05-01 02010-06-01 02010-07-01 02010-08-01 02010-09-01 12010-10-01 12010-11-01 1 R F2010-01-01 0 22010-02-01...
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 ?
l = [ ' A:1 ' , ' B:2 ' , ' C:3 ' , 'D:4 ' ] mydict = { } for e in l : k , v = e.split ( ' : ' ) mydict [ k ] = v
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 need to che...
from random import randintdef gen_interval ( min , max ) : return sorted ( ( randint ( min , max ) , randint ( min , max ) ) ) sample = sorted ( [ gen_interval ( 0 , 100 ) for _ in xrange ( 5 ) ] + [ gen_interval ( 101 , 200 ) for _ in xrange ( 5 ) ] , key=lambda ( a , b ) : ( a , b - a ) ) def intersects ( interval1 ,...
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 type ( fac...
class A : def __init__ ( self , x , y ) : self.x = x self.y = y def sum ( self ) : return self.x + self.y def factory ( x , y ) : class B : pass b = B ( ) setattr ( b , ' x ' , x ) setattr ( b , ' y ' , y ) B.__name__ = ' A ' return b
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 : User has...
def complex_api_function ( number , < lots of positional arguments > , < lots of keyword arguments > ) : `` 'really long docstring '' ' # lots of code def my_complex_api_function ( number_or_str , *args , **kwargs ) : `` ' Do something complex . Like ` complex_api_function ` , but first argument can be a string . Param...
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 ( `` '' `` '' string ...
type ( `` '' string `` '' ) type ( `` ' '' string `` ' '' )
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 realized that ...
[ 3 , 0 , 2 ] = 3^1 + 0^2 + 2^3 = 11 sum ( a ** i * j for i , j in enumerate ( l , 0 ) ) [ 3 , 0 , 2 ] = 4^0*3 + 4^1*0 + 4^2^2 = 35
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 : )
> > > a = [ 1 ] > > > b = [ 2 ] > > > a.append ( b ) > > > b.append ( a ) > > > sys.getrefcount ( a ) = 3 > > > sys.getrefcount ( b ) = 3 > > > GNU = [ 'is not Unix ' ] > > > GNU.insert ( 0 , GNU ) > > > sys.getrefcount ( GNU ) = 4
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 already existi...
uploader = request.session [ 'uploader ' ] Date=request.session [ 'date ' ] from django.core.files.storage import FileSystemStoragefrom financialdata.storage import OverwriteStorageclass XXXXDataForm ( forms.Form ) : XXXXfile=forms.FileField ( label='Select a file ' ) from django.core.files.storage import FileSystemSto...
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 time for tot...
import multiprocessingimport randomimport timeold_patterns = [ [ random.uniform ( -1 , 1 ) for _ in range ( 0 , 10 ) ] for _ in range ( 0 , 2000 ) ] new_patterns = [ [ random.uniform ( -1 , 1 ) for _ in range ( 0 , 10 ) ] for _ in range ( 0 , 100 ) ] new_pattern_for_processing = multiprocessing.Array ( 'd ' , 10 ) ther...
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 deal of c...
import collectionsimport glob import itertoolsimport typesig = glob.iglob ( '* ' ) iz = itertools.izip ( [ 1,2 ] , [ 3,4 ] ) > > > isinstance ( ig , types.GeneratorType ) True > > > isinstance ( iz , types.GeneratorType ) False > > > isinstance ( ig , collections.Iterator ) True > > > isinstance ( iz , collections.Iter...
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 know I c...
chars = [ ' a ' , ' b ' , ' c ' , 'd ' ] # outputoutput = [ [ ' a ' , ' b ' , ' c ' , 'd ' ] , [ 'ab ' , ' c ' , 'd ' ] , [ ' a ' , 'bc ' , 'd ' ] , [ ' a ' , ' b ' , 'cd ' ] , [ 'ab ' , 'cd ' ] , [ 'abc ' , 'd ' ] , # this one will be exempted [ ' a ' , 'bcd ' ] , # this one will be exempted [ 'abcd ' ] ] # this one w...
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 to be rei...
def f1 ( arg ) : def f2 ( ) : print arg def f3 ( ) : print arg f2 ( ) return f3x = SerialiseFunction ( f1 ( stuff ) ) # a stringsave ( x ) # save it somewhere # later , possibly in a different processx = load ( ) # get it from somewhere newf2 = DeserialiseFunction ( x ) newf2 ( ) # prints value of `` stuff '' twice def...
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 :
someone can tell/figurea/the squeaky wheel gets the grease/oilaccounts for ( someone or something ) that's/there 's ( something/someone ) for you someone can tellsomeone can figurea squeaky wheel gets the greasea squeaky wheel gets the oilthe squeaky wheel gets the greasethe squeaky wheel gets the oilaccounts for someo...
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 & check ind...
+ -- -- -- -- -- -- -- -- -- -- -- +| Items |+ -- -- -- -- -- -- -- -- -- -- -- +| X1 , Y1 , Z1 || X2 , Z3 || X3 || X1 , X2 || Y2 , Y4 , Z2 , Y5 , Z3 || X2 , X3 , Y1 , Y2 , Z2 , Z4 , X1 |+ -- -- -- -- -- -- -- -- -- -- -- + + -- -- -- -- -- -- -- -- -- -- -- + -- -- -- -- -- -- -- +| Items | Category |+ -- -- -- -- -- ...
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 appended ...
> > > x = range ( 3 ) [ 0 , 1 , 2 ] > > > x.append ( x ) [ 0 , 1 , 2 , [ ... ] ] > > > x [ 3 ] [ 3 ] [ 3 ] [ 3 ] [ 0 ] = 5 [ 5 , 1 , 2 , [ ... ] ] > > > x = range ( 3 ) [ 0 , 1 , 2 ] > > > x.append ( range ( 3 ) ) [ 0 , 1 , 2 , [ 0 , 1 , 2 ] ]
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 ?
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 output does...
import csvdata= [ [ 'fruit ' , 'quantity ' ] , [ 'apple',5 ] , [ 'banana',7 ] , [ 'mango',8 ] ] with open ( 'd : \lineter.csv ' , ' w ' ) as l : w=csv.writer ( l , delimiter='| ' , lineterminator='\r ' ) w.writerows ( data ) fruit|quantityapple|5banana|7mango|8 w=csv.writer ( l , delimiter='| ' , lineterminator='*\r*\n...
'\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 viaIf x ...
out [ i0 , i1 , ... , j0 , j1 , ... ] == prod ( x [ : , i0 , i1 , ... ] ** k [ : , j0 , j1 , ... ] ) import numpyx = numpy.random.rand ( 2 , 31 ) k = numpy.random.randint ( 1 , 10 , size= ( 2 , 101 ) ) out = numpy.prod ( x [ ... , None ] **k [ : , None ] , axis=0 ) x = numpy.random.rand ( 2 , 31 , 32 , 33 ) k = numpy.r...
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 :
mydict = { 1:5,2:7,3:9,4:9,7:7,8:0,111:43,110:77 } def partial_duplicate_destroyer ( mydict , tolerance ) : for key1 in mydict.keys ( ) : mydict_copy = mydict.copy ( ) for key2 in mydict_copy.keys ( ) : if key2 - tolerance < key1 < key2 + tolerance and not ( key1 == key2 ) : del ( mydict [ key1 ] ) break return mydictp...
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 example t...
_ d / / \ b c _e / / |a f g { 'bde ' , 'bcde ' , 'abde ' , 'abcde ' , 'bdfe ' , 'bdfge ' , 'abdfe ' , ... } class N ( ) : `` '' '' Node '' '' '' def __init__ ( self , name , lefts , rights ) : self.name = name self.lefts = lefts self.rights = rightstree = N ( 'd ' , [ N ( ' b ' , [ N ( ' a ' , [ ] , [ ] ) ] , [ ] ) , N...
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 be a ran...
from random import randintname1 = `` domingues '' name2 = `` signorelli '' names = [ name1 , name2 ] # a list of the desired lengthslengths = [ 5,6,7 ] mixes = [ ] def sizes ( size ) : if size == 5 : letters1 = randint ( 2,3 ) else : letters1 = randint ( 2 , size-2 ) letters2 = size-letters1 return letters1 , letters2d...
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 f 's exi...
import Tkinterclass C ( object ) : def __init__ ( self ) : self.root = Tkinter.Tk ( ) def f ( ) : print 'hello ' self.button = Tkinter.Button ( master=self.root , command=f , text='say hello ' ) import Tkinterclass C ( object ) : def __init__ ( self ) : self.root = Tkinter.Tk ( ) self.button = Tkinter.Button ( master=s...
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_df : The o...
lst= [ 'orange ' , 'apple ' , 'banana ' , 'grape ' , 'lemon ' ] Source Destination Weightorange apple 0.4banana orange 0.67grape lemon 0.1grape banana 0.5 Source Destination Weightorange apple 0.4banana orange 0.67grape lemon 0.1grape banana 0.5orange grape 0.0orange lemon 0.0banana lemon 0.0
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 ( ) so I ...
filters = Q ( is_default = False ) # Build the excludes and filters dynamically if cut : filters = filters & Q ( mailbagstats__num_letters2__gt = int ( cut ) )
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 imports ...
if __name__ == `` __main__ '' and __package__ is None : __package__ = `` expected.package.name '' foo├── bar.py└── baz.py if __name__ == `` __main__ '' and __package__ is None : __package__ = `` foo '' from . import baz PYTHONPATH= $ ( pwd ) python3 foo/bar.py python3 -m foo.bar if __package__ : from . import bazelse :...
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 ?
with open ( `` file '' ) as f : for line in f : print line with open ( `` file '' ) as f : data = f.readlines ( ) for line in data : print line
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 such : This ...
# using defaultdictlookup = collections.defaultdict ( list ) for item in items : lookup [ key ( item ) ] .append ( item ) # or , using plain dictlookup = { } for item in items : lookup.setdefault ( key ( item ) , [ ] ) .append ( item ) def grouped ( iterable , key ) : result = { } for item in iterable : result.setdefau...
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 tensor M of r...
T = [ x1 , x2 , x3 , x4 ] [ x1 , x2+x1·p , x3+ ( x2+x1·p ) ·p , x4+ ( x3+ ( x2+x1·p ) ·p ) *p ] import tensorflow as tf @ tf.functiondef vectorize_predec ( t , p ) : last_elem = 0 result = [ ] for el in t : result.append ( el + ( p * last_elem ) ) last_elem = el + ( p * last_elem ) return resultp = tf.Variable ( 0.5 , ...
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 .
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 .
import pandas as pdtcd = pd.DataFrame ( { ' a ' : { 'p_1 ' : 1 , 'p_2 ' : 1 , 'p_3 ' : 0 , 'p_4 ' : 0 } , ' b ' : { 'p_1 ' : 0 , 'p_2 ' : 1 , 'p_3 ' : 1 , 'p_4 ' : 1 } , ' c ' : { 'p_1 ' : 0 , 'p_2 ' : 0 , 'p_3 ' : 1 , 'p_4 ' : 0 } } ) tcd # a b c # p_1 1 0 0 # p_2 1 1 0 # p_3 0 1 1 # p_4 0 1 0 a & b = ab - > 1 or True...
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 . )
> > > a = { 'test1.1 ' : 5 } > > > 'test : { test1.1 } '.format ( **a ) KeyError : 'test1 '
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 . And also ...
d = { 'df1 ' : [ 10,20 , 30 , 60 , 70 , 40 , 30 , 70 ] , 'df2 ' : [ 20 , 30 , 40 , 80 , 70 , 50 , 90 , 100 ] } df = pd.DataFrame ( data = d ) df df1 df20 10 201 20 302 30 403 60 804 80 705 40 506 30 907 70 100 df1 | df2 -- -- -| -- -- -- -- -- -- -- -- -- -0 10 | 20 , 30 , 40 , 50 , 901 20 | 30 , 40 , 50 , 902 30 | 40 ...
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 ?
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 values f...
data = [ { 'response ' : 'This is a response ' , 'review ' : 'This is a review ' } , { 'review ' : 'This is only a review ' } , { 'response ' : 'This is also a response ' , 'review ' : 'This is also a review ' } ] date = [ ' 4 days ago ' , ' 3 days ago ' ] responder = [ 'Manager ' , 'Customer service ' ] for d in data ...
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 play in limi...
import matplotlibmatplotlib.use ( ‘ agg ’ ) import matplotlib.pyplotfig , ax = matplotlib.pyplot.subplots ( ) # ... fig.savefig ( “ thefig.pdf ” ) fig.savefig ( “ thefig.svg ” )
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 following ...
{ `` versionName '' : `` XXXXX/v8_0QSZ '' , `` dataFormat '' : `` JSON '' , `` inputPaths '' : [ `` XXXXX '' ] , `` outputPath '' : `` XXXXXX '' , `` region '' : `` us-east1 '' , `` runtimeVersion '' : `` 1.12 '' , `` accelerator '' : { `` count '' : `` 1 '' , `` type '' : `` NVIDIA_TESLA_P100 '' } } Exception during r...
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 ) .This is the...
test = [ ( 3 , 1 ) , ( 16 , 1 ) , ( 11 , 4 ) , ( 5 , 4 ) , ( 9 , 6 ) , ( 5 , 10 ) , ( 1 , 15 ) , ( 11 , 5 ) , ( 11 , 15 ) , ( 12 , 16 ) , ( 19 , 17 ) ] tree = create ( test ) def create ( point_list , presorted=False ) : if not point_list : return QuadNode ( ) if not presorted : point_list.sort ( key=lambda p : [ p [ 0...
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 care abou...
d1 = { ' a ' : [ ' a ' ] , ' b ' : [ ' b ' , ' c ' ] } d2 = { ' b ' : [ ' c ' , 'd ' ] , ' c ' : [ ' e ' , ' f ' ] } new_dict = { ' a ' : [ ' a ' ] , ' b ' : [ ' b ' , ' c ' , 'd ' ] , ' c ' : [ ' e ' , ' f ' ] } new_dict = { ' a ' : [ ' a ' ] , ' b ' : [ ' b ' , ' c ' , ' c ' , 'd ' ] , ' c ' : [ ' e ' , ' f ' ] } uni...
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 beginning ...
pat = re.compile ( `` ( ? = ( ATG ( ? : ( ? ! TAA|TGA|TAG ) \w\w\w ) * ) ) '' ) iters = pat.finditer ( s ) for it in iters : print it.start ( ) print it.end ( )
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
print ( `` This program will solve quadratic equations for you '' ) print ( `` It uses the system 'ax**2 + bx + c ' '' ) print ( `` a , b and c are all numbers with or without decimal \points '' ) print ( `` Firstly , what is the value of a ? `` ) a = float ( input ( `` \n\nType in the coefficient of x squared '' ) ) b...
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 :
import pandas as pdimport numpy as npdict = { `` A '' : [ [ 1,2,3,4 ] , [ 3 ] , [ 2,8,4 ] , [ 5,8 ] ] } dt = pd.DataFrame ( dict ) A B0 [ 1 , 2 , 3 , 4 ] [ 1,4 ] 1 [ 3 ] [ 3,3 ] 2 [ 2 , 8 , 4 ] [ 2,8 ] 3 [ 5 , 8 ] [ 5,8 ] dt [ `` B '' ] = [ np.min ( dt.A ) , np.max ( dt.A ) ]
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 question and ...
import itertools as itdef unique_group ( iterable , k , n ) : `` '' '' Return an iterator , comprising groups of size ` k ` with combinations of size ` n ` . '' '' '' # Build separate combinations of ` n ` characters groups = ( `` '' .join ( i ) for i in it.combinations ( iterable , n ) ) # 'AB ' , 'AC ' , 'AD ' , ... ...
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 .
[ ( 196 , 128 ) , ( 196 , 128 ) , ( 196 , 128 ) , ( 128 , 196 ) , ( 196 , 128 ) , ( 128 , 196 ) , ( 128 , 196 ) , ( 196 , 128 ) , ( 128 , 196 ) , ( 128 , 196 ) ] [ 128 , 196 ]
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 that bit o...
def fn1 ( ) : # @ my_decorator will be here def fn2 ( ) : pass print ( fn2 ) return fn2x = fn1 ( ) print ( x ) print ( x.__module__ ) < function fn1. < locals > .fn2 at 0x7fd61bdf3ae8 > < function fn1. < locals > .fn2 at 0x7fd61bdf3ae8 > __main__
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 be : If th...
[ `` 123 '' , '' 12+3 '' , '' 12-3 '' , '' 1+23 '' , '' 1+2+3 '' , '' 1+2-3 '' , '' 1-23 '' , '' 1-2+3 '' , '' 1-2-3 '' ] def options ( string ) : if len ( string ) == 1 : return string else : # This is where I am stuck
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 access in t...
CATEGORIES = [ ] with open ( 'Catergories.txt ' , ' r ' ) as f : data = f.readlines ( ) for category in data : CATEGORIES.append ( category.strip ( ) ) # -*- coding : utf-8 -*-from scrapy.linkextractors import LinkExtractorfrom scrapy.spiders import CrawlSpider , Rulefrom ..items import YellowItemfrom scrapy.utils.proj...
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 ?
import timesorted_list = range ( 0 , 10000000 ) needle = 9999999def split_list ( sorted_list ) : half = len ( sorted_list ) /2 return sorted_list [ : half ] , sorted_list [ half : ] def bisection ( haystack , needle , length_of_list ) : if len ( haystack ) < = length_of_list/5 : return haystack first , last = split_lis...
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 this is the...
self.assertTrue ( isinstance ( result , Sequence ) or isinstance ( result , GeneratorType ) or callable ( getattr ( result , '__reversed__ ' , False ) ) )
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 I do n't ...
from functools import wrapsdef logging_decorator ( tricky_instance ) : def wrapper ( fn ) : @ wraps ( fn ) def wrapped ( *a , **kw ) : if tricky_instance.log : print ( `` Calling % s.. '' % fn.__name__ ) return fn ( *a , **kw ) return wrapped return wrapper class Tricky ( object ) : def __init__ ( self , log ) : self.l...
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.charmap_deco...
< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > from bs4 import BeautifulSoupfd = open ( `` xmlsample.xml '' ) soup = BeautifulSoup ( fd , 'lxml-xml ' , from_encoding='utf-8 ' ) Traceback ( most recent call last ) : File `` C : \Users\gregg_000\Desktop\Python Experiments\NRE_XMLtoCSV\NRE_XMLtoCSV\bs1.py '' , line ...
handling encoding error with xml with beautiful soup