lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | What 's the name for the square brackets syntax in this snippet ? And - just to clarify - is it accessing the default field inside 'label ' and changing that ? I seem to think it is called 'binding ' - but I 've got literally no idea where I got that idea from | def change_text ( ) : label [ `` text '' ] = entry.get ( ) | Square brackets next to an object - What 's the notation called ? |
Python | How does a super method actually works in python ? In the given code : when test is called on D , it output B- > C instead of B- > A ( which I was expecting ) .How is super inside B referring to an instance of C ? | class A ( object ) : def test ( self ) : return ' A'class B ( A ) : def test ( self ) : return ' B- > '+super ( B , self ) .test ( ) class C ( A ) : def test ( self ) : return ' C'class D ( B , C ) : passprint B ( ) .test ( ) # B- > Aprint D ( ) .test ( ) # B- > C ? ? ? ? # MRO of classes are asprint 'mro of A ' , A.__... | How does a super method work in python in case of multiple inheritance ? |
Python | I am trying to learn f2py and I have the following Fortran codewhich is compiled with f2py -c fibonacci.f -m fibonacci and later called in PythonThe subroutine fibonacci called in Python did not get enough number of arguments , but the code mysteriously worked . By the way , calling the subroutine fibonacci with fibona... | subroutine fibonacci ( a , n ) implicit none integer : : i , n double precision : : a ( n ) do i = 1 , n if ( i .eq . 1 ) then a ( i ) = 0d0 elseif ( i .eq . 2 ) then a ( i ) = 1d0 else a ( i ) = a ( i - 1 ) + a ( i - 2 ) endif enddo end subroutine fibonacci import numpyimport fibonaccia = numpy.zeros ( 13 ) fibonacci.... | Why can I call Fortran subroutine through f2py without having right number of inputs ? |
Python | I 've just noticed something strange and was wondering if someone could explain what 's going on ? I have a dictionary i 'm plotting a horizontal and vertical bar charts from.if dictionary is unhashable , why does it let me plot a normal bar graph ? Is this just a quirk of the barh function or am I doing something wron... | plt.bar ( food.keys ( ) , food.values ( ) ) # works fine , but : plt.barh ( food.keys ( ) , food.values ( ) # gives `` unhashable type : 'dict_keys ' '' error . food = { 'blueberries':2 , 'pizza':3.50 , 'apples':0.50 } | matplotlib 'bar ' vs 'barh ' plots . Problem with barh |
Python | I 'm trying to catch firstnames by making the assumtion that they are on the form Firstname Lastlame . This works good with the code below , but I would like to be able to catch international names like Pär Åberg . I found some solutions but they does unfortunally not seem to work with Python flavoured regexp . Anyone ... | # ! /usr/bin/python # -*- coding : utf-8 -*- import retext = `` '' '' This is a text containing names of people in the text such as Hillary Clinton or Barack Obama . My problem is with names that uses stuff outside A-Z like Swedish names such as Pär Åberg . `` `` '' for name in re.findall ( `` ( ( [ A-Z ] ) [ \w- ] * (... | Matching names on form Firstname Lastname with international characters |
Python | Assume for a given number N , generated a matrix which has N+1 rows , and each rows has N columns , each columns has N number in range [ 1 , N^2 ] . And the matrix has this feature : every column has N number , the numbers are totally distributed in other row . Sorry for that English is not my mother language , I tried... | [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] [ 1 , 4 , 7 ] , [ 2 , 5 , 8 ] , [ 3 , 6 , 9 ] [ 1 , 5 , 9 ] , [ 2 , 6 , 7 ] , [ 3 , 4 , 8 ] [ 1 , 6 , 8 ] , [ 2 , 4 , 9 ] , [ 3 , 5 , 7 ] [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 ] [ 1 , 5 , 9 , 13 ] , [ 2 , 6 , 10 , 14 ] , [ 3 , 7 ... | How to build a N* ( N+1 ) matrix with number in range of 1~N*N and totally distributed ? |
Python | I am trying to extend a str and override the magic method __cmp__ . The below example shows that the magic method __cmp__ is never called when > is used : when run results in : Obviously , when using the > the underlying `` compare '' functionality within the builtin is getting called , which in this case is an alphabe... | class MyStr ( str ) : def __cmp__ ( self , other ) : print ' ( was called ) ' , return int ( self ) .__cmp__ ( int ( other ) ) print 'Testing that MyStr ( 16 ) > MyStr ( 7 ) 'print ' -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -'print 'using _cmp__ : ' , MyStr ( 16 ) .__cmp__ ( MyStr ( 7 ) ) print 'using > : ' , My... | Can you override a magic method when extending a builtin in python ? |
Python | Programming language : Python 3.4I have written a program for the Bioinformatics 1 course from Coursera . The program is working all right , but is very slow for large datasets . I guess , it is because the loop is running for 4**k times , where k is the length of the sub-string that is passed into the function.Input :... | def MotifCount ( string1 , substring , d ) : k = 4 ** ( len ( substring ) ) codeArray = list ( itertools.product ( [ ' A ' , ' C ' , ' G ' , 'T ' ] , repeat=len ( substring ) ) ) for i in range ( k ) : codeArray2 = `` .join ( list ( codeArray [ i ] ) ) HammingValue = HammingDistance ( codeArray2 , substring ) if Hammin... | How to optimize a python script which runs for 4**k times ? |
Python | In python , a value x is not always constrained to equal itself . Perhaps the best known example is NaN : Now consider a list of exactly one item . We might consider two such lists to be equal if and only the items they contained were equal . For example : But this does not appear to be the case with NaN : So these lis... | > > > x = float ( `` NaN '' ) > > > x == xFalse > > > [ `` hello '' ] == [ `` hello '' ] True > > > x = float ( `` NaN '' ) > > > x == xFalse > > > [ x ] == [ x ] True > > > x = float ( `` NaN '' ) > > > [ x ] == [ x ] True > > > [ x ] == [ float ( `` NaN '' ) ] False | Comparison of collections containing non-reflexive elements |
Python | I am trying to run a simulation to test the average Levenshtein distance between random binary strings.To speed it up I am using this C extension.My code is as follows.I think the slowest part is now the string generation . Can that be sped up somehow or is there some other speed up I could try ? I also have 8 cores bu... | from Levenshtein import distance for i in xrange ( 20 ) : sum = 0 for j in xrange ( 1000 ) : str1 = `` .join ( [ random.choice ( `` 01 '' ) for x in xrange ( 2**i ) ] ) str2 = `` .join ( [ random.choice ( `` 01 '' ) for x in xrange ( 2**i ) ] ) sum += distance ( str1 , str2 ) print sum/ ( 1000*2**i ) | Optimising string generate and test |
Python | suppose that I have a dataframe as follows : I 'm trying to filter the numbers that are repeated 4 times or more and the output will be : Right now I 'm using itemfreq to extract that information , this results in a series of arrays where then is complicated to make a conditional and to filter only these numbers . I th... | df = pd.DataFrame ( { ' A ' : [ 1,1,2,3,3,3,3,3,4,4,4,4,4,4,4,5,5,5,5,6,6 ] } ) dfOut [ 1 ] : A 0 1 1 1 2 2 3 3 4 3 5 3 6 3 7 3 8 4 9 4 10 4 11 4 12 4 13 4 14 4 15 5 16 5 17 5 18 5 19 6 20 6 df1Out [ 2 ] : A0 31 32 33 34 35 46 47 48 49 410 411 412 513 514 515 5 | with python , select repeated elements longer than N |
Python | I 'm using python to implement another programming language named 'foo ' . All of foo 's code will be translated to python , and will also be run in the same python interpreter , so it will JIT translate to python.Here is a small piece of foo 's code : which will translate to : The 'watchdog ' is a greenlet ( the gener... | function bar ( arg1 , arg2 ) { while ( arg1 > arg2 ) { arg2 += 5 ; } return arg2 - arg1 ; } def _bar ( arg1 , arg2 ) : while arg1 > arg2 : arg2 += 5 watchdog.switch ( ) watchdog.switch ( ) return arg2 - arg1 1 function bar ( ) { 2 throw Exception ( 'Some exception message ' ) ; 3 } 45 function foo ( ) { 6 output ( 'inv... | How to add traceback/debugging capabilities to a language implemented in python ? |
Python | I am trying to use Hamiltonian Monte Carlo ( HMC , from Tensorflow Probability ) but my target distribution contains an intractable 1-D integral which I approximate with the trapezoidal rule . My understanding of HMC is that it calculates gradients of the target distribution to build a more efficient transition kernel ... | # integrate e^At * f [ t ] with respect to t between 0 and t , for all tt = tf.linspace ( 0. , 10. , 100 ) f = tf.ones ( 100 ) delta = t [ 1 ] -t [ 0 ] sum_term = tfm.multiply ( tfm.exp ( A*t ) , f ) integrals = 0.5*delta*tfm.cumsum ( sum_term [ : -1 ] + sum_term [ 1 : ] , axis=0 ) pred = integralssq_diff = tfm.square ... | Can Tensorflow work out gradients for integral approximations ? |
Python | How do I find the indices of the first two elements in a list that are any of the elements in another list ? For example : In this case , the desired output is a list indices = [ 0,2 ] for strings ' a ' and ' c ' . | story = [ ' a ' , ' b ' , ' c ' , 'd ' , ' b ' , ' c ' , ' c ' ] elementsToCheck = [ ' a ' , ' c ' , ' f ' , ' h ' ] | How to find indices of first two elements in a list that are any of the elements in another list ? |
Python | When slicing in python , omitting the end portion of the slice ( ie the end in list [ : end : ] ) results in end being defined as `` the size of the string being sliced . '' *However , this does n't seem to hold true when using the step argument ( the step in list [ : :step ] ) in a slice , at least when the step argum... | > > > l = [ 1 , 2 , 3 ] > > > l [ : :-1 ] [ 3 , 2 , 1 ] > > > l [ : len ( l ) : -1 ] [ ] | Why does list [ : :-1 ] not equal list [ : len ( list ) : -1 ] ? |
Python | For example , given : I want to get a 3-dimensional array , looking like : One way is : What I 'm trying to do is the following : This does n't seem to work and I would like to achieve the desired result by sticking to my implementation rather than the one mentioned in the beginning ( or using any extra imports , eg co... | import numpy as npdata = np.array ( [ [ 0 , 0 , 0 ] , [ 0 , 1 , 1 ] , [ 1 , 0 , 1 ] , [ 1 , 0 , 1 ] , [ 0 , 1 , 1 ] , [ 0 , 0 , 0 ] ] ) result = array ( [ [ [ 2. , 0 . ] , [ 0. , 2 . ] ] , [ [ 0. , 2 . ] , [ 0. , 0 . ] ] ] ) for row in data newArray [ row [ 0 ] ] [ row [ 1 ] ] [ row [ 2 ] ] += 1 for i in dimension1 for... | Python : Counting identical rows in an array ( without any imports ) |
Python | Works : Does n't work : But why not ? I thought 'self ' was just a convention , and there was nothing intrinsically special about this argument ? | > > > class Potato ( object ) : ... def method ( self , spam ) : ... print self , spam ... > > > spud = Potato ( ) > > > Potato.method ( spud , ** { 'spam ' : 123 } ) < __main__.Potato object at 0x7f86cd4ee9d0 > 123 > > > Potato.method ( ** { 'self ' : spud , 'spam ' : 123 } ) # TypeError | Why ca n't we **unsplat 'self ' into a method ? |
Python | I need to create a map from twitter status IDs to their author ID.Obviously , each status has exactly one author.I expected Python collections to have something like uniqdict class for which d [ key ] = value will raise an exception if the key already has a value different from value : Q : Is there a standard name for ... | class uniqdict ( dict ) : def __setitem__ ( self , key , value ) : try : old = super ( uniqdict , self ) .__getitem__ ( key ) if old ! = value : raise ValueError ( self.__class__.__name__ , key , old , value ) except KeyError : super ( uniqdict , self ) .__setitem__ ( key , value ) | A dictionary with a unique possible value for each key ? |
Python | All of a sudden i got a list with 2 elems , but how ? Should n't b be getting set to empty list every time . Thanks for the help | def a ( b= [ ] ) : b.append ( 1 ) return bprint a ( ) print a ( ) | do not understand closures question in python |
Python | Every object in sympy is a subclass of the Basic class , and they all use __new__ without __init__ , and mostly it 's something likeWhat 's the difference to using __init__ like ? | def __new__ ( cls , some , parameter , **others ) : obj = parentclass.__new__ ( cls , **others ) obj.some = some obj.parameter = parameter return obj def __init__ ( self , some , parameter , **others ) : parentclass.__init__ ( self , **others ) # or super ( ) .__init__ ( ... ) self.some = some self.parameter = paramete... | Why does sympy override ` __new__ ` instead of ` __init__ ` ? |
Python | I have four multidimensional tensors v [ i , j , k ] , a [ i , s , l ] , w [ j , s , t , m ] , x [ k , t , n ] in Numpy , and I am trying to compute the tensor z [ l , m , n ] given by : z [ l , m , n ] = sum_ { i , j , k , s , t } v [ i , j , k ] * a [ i , s , l ] * w [ j , s , t , m ] * x [ k , t , n ] All the tensor... | z = np.einsum ( 'ijk , isl , jstm , ktn ' , v , a , w , x ) z = np.zeros ( ( a.shape [ -1 ] , w.shape [ -1 ] , x.shape [ -1 ] ) ) for s in range ( a.shape [ 1 ] ) : for t in range ( x.shape [ 1 ] ) : res = np.tensordot ( v , a [ : ,s , : ] , ( 0,0 ) ) res = np.tensordot ( res , w [ : ,s , t , : ] , ( 0,0 ) ) z += np.te... | Efficient reduction of multiple tensors in Python |
Python | After reading http : //www.effbot.org/zone/python-objects.htm I am left with this question : In python , if a=1 creates an integer-object and binds it to the name a , b= [ ] creates an empty list-object and binds it to name b , what happens when I call e.g . c= [ 1 ] ? I suppose this creates a list-object and binds it ... | d=1 # creates int ( 1 ) -object and binds it to de= [ d ] # creates list-object and binds it to e , but what happens with d ? | What happens when I create a list such as c= [ 1 ] in python , in terms of name object bindings ? |
Python | Is it pythonic to use or , similar to how PHP would use or die ( ) ? I have been usingquiet or print ( stuff ) instead ofif verbose : print ( stuff ) lately . I think it looks nicer , they do the same thing , and it saves on a line . Would one be better than the other in terms of performance ? The bytecode for both loo... | 2 0 LOAD_FAST 0 ( quiet ) 3 JUMP_IF_TRUE_OR_POP 15 6 LOAD_GLOBAL 0 ( print ) 9 LOAD_CONST 1 ( 'foo ' ) 12 CALL_FUNCTION 1 ( 1 positional , 0 keyword pair ) > > 15 POP_TOP 16 LOAD_CONST 0 ( None ) 19 RETURN_VALUE 2 0 LOAD_FAST 0 ( verbose ) 3 POP_JUMP_IF_FALSE 19 3 6 LOAD_GLOBAL 0 ( print ) 9 LOAD_CONST 1 ( 'bar ' ) 12 ... | Would it be pythonic to use ` or ` , similar to how PHP would use ` or die ( ) ` ? |
Python | The desired result : When I applied each of the codes below , the parentheses and the whitespace before them were not replaced : orThe obtained result : | + -- -+ -- -- -- -- -- -- +| A| B|+ -- -+ -- -- -- -- -- -- +| x1| [ s1 ] || x2| [ s2 ( A2 ) ] || x3| [ s3 ( A3 ) ] || x4| [ s4 ( A4 ) ] || x5| [ s5 ( A5 ) ] || x6| [ s6 ( A6 ) ] |+ -- -+ -- -- -- -- -- -- + + -- -+ -- -- -- -- -- -- + -- -- -- -+|A |B |value |+ -- -+ -- -- -- -- -- -- + -- -- -- -+|x1 | [ s1 ] | [ s1 ... | Replace parentheses in pyspark with replace_regex |
Python | I have been trying to search on how to get the value of the first column and append it to the remaining columns in the dataframe but the ones that I have seen need to still make a new column for the new output.The closest that I found based on what I need is this code.Below is a sample of my dataframeWhat I want to kno... | df [ 'col ' ] = 'str ' + df [ 'col ' ] .astype ( str ) col1 col2 col3 col41 02-04-2017 ND 0.32 0.82 02-05-2017 0.3 ND No Connection col1 col2 c ol3 col41 02-04-2017 ND|02-04-2017 0.32|02-04-2017 0.8|02-04-2017 2 02-05-2017 0.3|02-05-2017 ND|02-05-2017 No Connection|02-05-2017 | How do you append the values of the first column to all other columns in a pandas dataframe |
Python | Consider the following idea : I want to generate a sequence of functions f_k , for k = 1 , ... ,50 and store them in a Python dictionary . To give a concrete example , lets say This is just an example , the problem I have is more complicated , but this does not matter for my question . Because in my real problem f_ { k... | f_k ( x ) = f_ { k-1 } ( x ) * sqrt ( x ) import numpy as npfrom scipy.interpolate import interp1dn = 50 # number of functions I want to createargs = np.linspace ( 1,4,20 ) # where to evaluate for spline approximationfdict = dict ( ) # dictionary that stores all the functionsfdict [ 0 ] = lambda x : x**2 # the first fu... | Iterative function generation in Python |
Python | How do I cut a string based on digit first certain digit and the restHere 's my dataHere 's the expected outputfor cut_pattern1 is the first 4 digits from actual_patternfor cut_pattern2 is the rest form from cut_pattern1 , if the rest from cut_pattern1 is not exist make cut_pattern2 = 0If any 1 in cut_pattern2 , make b... | Id actual_pattern1 1001012 101013 10101014 101 Id actual_pattern cut_pattern1 cut_pattern2 binary_cut21 100101 1001 01 12 10101 1010 1 13 1010101 1010 101 14 101 101 0 0 | How do I cut a string based on digit first certain digit and the rest |
Python | I have a list of possibilities and a desired input : I want to generate the close by lists . Example : My current version is only varying one element at a time , thus , as soon as the distance is above 1 , I 'm missing a lot of combination.I 'm quite sure a module should already exist to do this kind of iteration ( ite... | possibles = [ 20 , 30 , 40 , 50 , 60 , 70 , 80 , 100 ] desired = [ 20 , 30 , 40 ] # Distance of 1 ( i.e . 1 element changes to a close-by ) [ 30 , 30 , 40 ] [ 20 , 40 , 40 ] [ 20 , 30 , 30 ] [ 20 , 30 , 50 ] # Distance of 2 : [ 40 , 30 , 40 ] [ 30 , 30 , 50 ] [ 30 , 40 , 40 ] ... def generate_close_by ( possibles , des... | How to generates a list which elements are at a fix distance from a desired list |
Python | I 'm coding some J bindings in Python ( https : //gist.github.com/Synthetica9/73def2ec09d6ac491c98 ) . However , I 've run across a problem in handling arbitrary-precicion integers : the output does n't make any sense . It 's something different everytime ( but in the same general magnitude ) . The relevant piece of co... | def JTypes ( desc , master ) : newdesc = [ item.contents.value for item in desc ] type = newdesc [ 0 ] if debug : print type rank = newdesc [ 1 ] shape = ct.c_int.from_address ( newdesc [ 2 ] ) .value adress = newdesc [ 3 ] # string if type == 2 : charlist = ( ct.c_char.from_address ( adress+i ) for i in range ( shape ... | J 's x-type variables : how are they stored internally ? |
Python | I 'm relatively new here , so please tell me if there is anything I should know or any mistakes I am making manner wise ! I am trying to add things onto a dictionary through random choice , but my code does n't seem to work ! The file : sports.txtmy code so far : I am trying to allow a user to input their name and pref... | Soccer , JoshuaLacrosse , Naome LeeSoccer , Kat ValentineBasketball , HuongTennis , SunnyBasketball , Freddie Lacer def sportFileOpen ( ) : sportFile = open ( `` sport.txt '' ) readfile = sportFile.readlines ( ) sportFile.close ( ) return ( readfile ) def sportCreateDict ( sportFile ) : sportDict = { } for lines in spo... | Adding element to a dictionary in python ? |
Python | I have a pairwise matrix : I want to replace the NaN in the the top right with the same values as in the bottom left : I can do it by swapping columns and indexes : But that 's slow with my actual data , and I 'm sure there 's a way to do it in one step . I know I can generate the upper right version with `` m.T '' but... | > > > m a b c da 1.0 NaN NaN NaNb 0.5 1.0 NaN NaNc 0.6 0.0 1.0 NaNd 0.5 0.4 0.3 1.0 > > > m2 a b c da 1.0 0.5 0.6 0.5b 0.5 1.0 0.0 0.4c 0.6 0.0 1.0 0.3d 0.5 0.4 0.3 1.0 cols = m.columnsidxs = m.indexfor c in cols : for i in idxs : m [ i ] [ c ] = m [ c ] [ i ] | Fill matrix with transposed version |
Python | Consider a library function with the following signature : Let 's look at some simple code that consumes it : Nothing interesting so far . But let 's say we do n't care for even numbers . Only numbers that are odd , like us : Now let 's try an implementation of get_numbers : Nothing very interesting here . The results ... | from typing import Iteratordef get_numbers ( ) - > Iterator [ int ] : ... for i in get_numbers ( ) : print ( i ) for i in get_numbers ( ) : if i & 1 == 0 : raise ValueError ( `` Ew , an even number ! '' ) print ( i ) def get_numbers ( ) - > Iterator [ int ] : yield 1 yield 2 yield 3 > > > for i in get_numbers ( ) : 2 i... | How do I ensure that a generator gets properly closed ? |
Python | I have a form inside a modal that I use to edit a review on an item ( a perfume ) . A perfume can have multiple reviews , and the reviews live in an array of nested documents , each one with its own _id.I 'm editing each particular review ( in case an user wants to edit their review on the perfume once it 's been submi... | @ reviews.route ( `` /review '' , methods= [ `` GET '' , `` POST '' ] ) @ login_requireddef edit_review ( ) : form = EditReviewForm ( ) review_id = request.form.get ( `` review_id '' ) perfume_id = request.form.get ( `` perfume_id '' ) if form.validate_on_submit ( ) : mongo.db.perfumes.update ( { `` _id '' : ObjectId (... | Pre-populate current value of WTForms field in order to edit it |
Python | I have a model that calls a file parser ( to parse a file ) and that file parser calls the model to save the object . Currently , the code looks something like this : models.pyingest.pyThis 'works ' fine , however , doing the import within the save method adds about 0.25s the first time I have to use it , as it 's init... | class Source ( models.Model ) : ... def parse_file ( self ) : from ingest.parser import FileParser ... class FileParser ( ) def save ( self ) : from models import Source ... | Resolving circular dependencies in a python/django application |
Python | While playing with ImportanceOfBeingErnest 's code to move artists between axes , I thought it would easy to extend it to collections ( such as PathCollections generated by plt.scatter ) as well . No such luck : yieldsRemoving artist.set_transform ( ax.transData ) ( at least when calling ax.add_collection ) seems to he... | import matplotlib.pyplot as pltimport numpy as npimport picklex = np.linspace ( -3 , 3 , 100 ) y = np.exp ( -x**2/2 ) /np.sqrt ( 2*np.pi ) a = np.random.normal ( size=10000 ) fig , ax = plt.subplots ( ) ax.scatter ( x , y ) pickle.dump ( fig , open ( `` /tmp/figA.pickle '' , `` wb '' ) ) # plt.show ( ) fig , ax = plt.s... | Moving Collections between axes |
Python | I have a list of elements like [ 1,3,5,6,8,7 ] .I want a list of sums of two consecutive elements of the list in a way that the last element is also added with the first element of the list.I mean in the above case , I want this list : [ 4,8,11,14,15,8 ] But when it comes to the addition of the last and the first eleme... | List1 = [ 1,3,5,6,8,7 ] List2 = [ List1 [ i ] + List1 [ i+1 ] for i in range ( len ( List1 ) ) ] print ( List2 ) | Sum of consecutive pairs in a list including a sum of the last element with the first |
Python | When writing a Python script that can be executed in different operating system environments ( Windows/*nix ) , what are some good ways to set a path ? In the example below I would like to have the logfiles stored in the logs folder under the current directory . Is this an acceptable approach ( I 'm rather new to Pytho... | if os.name == 'nt ' : logdir= ( ' % s\\logs\\ ' ) % ( os.getcwd ( ) ) else : logdir= ( ' % s/logs/ ' ) % ( os.getcwd ( ) ) logging.basicConfig ( level=logging.INFO , format= ' % ( asctime ) s % ( name ) -12s % ( levelname ) -8s % ( message ) s ' , datefmt= ' % m- % d- % y % H : % M : % S ' , filename= ' % slogfile.log ... | What are some good ways to set a path in a Multi-OS supported Python script |
Python | I was working on a project using OpenCV , Python that uses Probabilistic Hough Line Transform function `` HoughLinesP '' in some part of the project . My code worked just fine and there was no problem . Then I thought of converting the same code to C++.After converting the code to C++ , the output is not the same as th... | Lines = cv2.HoughLinesP ( EdgeImage , 1 , np.pi / 180 , 50 , 10 , 15 ) std : :vector < cv : :Vec4i > Lines ; cv : :HoughLinesP ( EdgeImage , Lines , 1 , CV_PI / 180 , 50 , 10 , 15 ) ; | OpenCV Probabilistic Hough Line Transform giving different results with C++ and Python ? |
Python | At work , I stumbled upon an except clause with an or operator : I know the exception classes should be passed as a tuple , but it bugged me that it would n't even cause a SyntaxError.So first I wanted to investigate whether it actually works . And it doesn't.So it did not catch the second exception , and looking at th... | try : # Do something.except IndexError or KeyError : # ErrorHandling > > > def with_or_raise ( exc ) : ... try : ... raise exc ( ) ... except IndexError or KeyError : ... print ( 'Got ya ! ' ) ... > > > with_or_raise ( IndexError ) Got ya ! > > > with_or_raise ( KeyError ) Traceback ( most recent call last ) : File `` ... | Why does using ` or ` within an except clause not cause a SyntaxError ? Is there a valid use for it ? |
Python | I found this memory leak detection snippet and was wondering about the memory leak it generated.In order to test the gc memory leak detection , the author created its own little mem leak : Why would that result in a leak ? As I see it , I would have a list object , and than a nested list object , where the inner is the... | import gcdef dump_garbage ( ) : `` '' '' show us what 's the garbage about `` '' '' # force collection print ( `` \nGARBAGE : '' ) gc.collect ( ) print ( `` \nGARBAGE OBJECTS : '' ) for x in gc.garbage : s = str ( x ) if len ( s ) > 80 : s = s [ :80 ] print ( type ( x ) , '' \n `` , s ) if __name__== '' __main__ '' : i... | Why appending list to itself , and then deleting , results in memory leak |
Python | I use .get ( ) to query for keys which may or may not be present in a dictionary.I have , however , dictionaries where the key I want to check for is deeper in the structure and I do not know if the ancestors are present or not . If the dict is b = { ' x ' : { ' y ' : { ' z ' : True } } } do I have to resort toto check... | In [ 1 ] : a = { 'hello ' : True } In [ 3 ] : print ( a.get ( 'world ' ) ) None In [ 5 ] : b.get ( ' x ' ) and b [ ' x ' ] .get ( ' y ' ) and b [ ' x ' ] [ ' y ' ] .get ( ' z ' ) Out [ 5 ] : True | how to use .get ( ) in a nested dict ? |
Python | I try to implement beam collision detection with a predefined track mask in Pygame . My final goal is to give an AI car model vision to see a track it 's riding on : This is my current code where I fire beams to mask and try to find an overlap : Let 's describe what happens in the code snippet . One by one , I draw bea... | import mathimport sysimport pygame as pgRED = ( 255 , 0 , 0 ) GREEN = ( 0 , 255 , 0 ) BLUE = ( 0 , 0 , 255 ) pg.init ( ) beam_surface = pg.Surface ( ( 500 , 500 ) , pg.SRCALPHA ) def draw_beam ( surface , angle , pos ) : # compute beam final point x_dest = 250 + 500 * math.cos ( math.radians ( angle ) ) y_dest = 250 + ... | Overlap between mask and fired beams in Pygame [ AI car model vision ] |
Python | I have a test that makes sure a specific ( helpful ) error message is raised , when a required package is not available.However , pkg is generally available , as other tests rely on it.Currently , I set up an additional virtual env without pkg just for this test . This seems like overkill.Is it possible to `` hide '' a... | def foo ( caller ) : try : import pkg except ImportError : raise ImportError ( f'Install `` pkg '' to use { caller } ' ) pkg.bar ( ) with pytest.raises ( ImportError , match='Install `` pkg '' to use test_function ' ) : foo ( 'test_function ' ) | Making a Python test think an installed package is not available |
Python | Given the following data frame : I would like to reshape it so it would look like so : So every 3 rows are grouped into 1 rowHow can I achieve this with pandas ? | pd.DataFrame ( { `` A '' : [ 1,2,3 ] , '' B '' : [ 4,5,6 ] , '' C '' : [ 6,7,8 ] } ) A B C0 1 4 61 2 5 72 3 6 83 11 14 164 12 15 175 13 16 18 A B C A_1 B_1 C_1 A_2 B_2 C_20 1 4 6 2 5 7 3 6 81 11 14 16 12 15 17 13 16 18 | Python Pandas - Reshape Dataframe |
Python | I 've been experimenting with a class that does pattern matching . My class looks something like this : All told , my script takes ~45 seconds to run . As an experiment , I changed my code to : A run of this script took 37 seconds . No matter how many times I repeat this process , I see the same significant boost in pe... | class Matcher ( object ) : def __init__ ( self , pattern ) : self._re = re.compile ( pattern ) def match ( self , value ) : return self._re.match ( value ) class Matcher ( object ) : def __init__ ( self , pattern ) : self._re = re.compile ( pattern ) self.match = self._re.match ncalls tottime percall cumtime percall fi... | Why does using an attribute instead of a method provide such a significant boost in Python speed |
Python | I have a method called import_customers ( ) which loads csv-like data.This methods logs to log-level INFO.In one case I want to avoid this logging.I see several ways : Variant 1 : a new kwarg like do_logging=True which I can switch to false.Variant 2 : Use some magic context which ignores this line.How could I implemen... | with IgnoreLoggingContext ( ) as context : import_customers ( ) | Ignore specific logging line temporarily |
Python | I have this list of dicts : I can sort by score with : sorted ( l , key=lambda k : k [ 'score ' ] , reverse=True ) . However I have tied scores . How can I sort first by score and then by id asc or desc ? | [ { 'score ' : ' 1.9 ' , 'id ' : 756 , 'factors ' : [ 1.25 , 2.25 , 2.5 , 2.0 , 1.75 ] } , { 'score ' : ' 2.0 ' , 'id ' : 686 , 'factors ' : [ 2.0 , 2.25 , 2.75 , 1.5 , 2.25 ] } , { 'score ' : ' 2.0 ' , 'id ' : 55 , 'factors ' : [ 1.5 , 3.0 , 2.5 , 1.5 , 1.5 ] } , { 'score ' : ' 1.9 ' , 'id ' : 863 , 'factors ' : [ 1.5... | Sort list of dicts by two keys |
Python | I have a list of lists : How can I merge it with a single list like : So that the end result looks like : Initially I tried : zip ( list_with_lists , list ) but data was obfuscated | [ [ 'John ' , 'Sergeant ' ] , [ 'Jack ' , 'Commander ' ] , [ 'Jill ' , 'Captain ' ] ] [ '800 ' , '854 ' , '453 ' ] [ [ 'John ' , 'Sergeant ' , '800 ' ] , [ 'Jack ' , 'Commander ' , '854 ' ] , [ 'Jill ' , 'Captain ' , '453 ' ] ] | Merging a list with a list of lists |
Python | I have four square matrices with dimension 3Nx3N , called A , B , C and D.I want to combine them in a single matrix.The code with for loops is the following : Is it possible to write the previous for loops in a numpythonic way ? | import numpyN = 3A = numpy.random.random ( ( 3*N , 3*N ) ) B = numpy.random.random ( ( 3*N , 3*N ) ) C = numpy.random.random ( ( 3*N , 3*N ) ) D = numpy.random.random ( ( 3*N , 3*N ) ) final = numpy.zeros ( ( 6*N , 6*N ) ) for i in range ( N ) : for j in range ( N ) : for k in range ( 3 ) : for l in range ( 3 ) : final... | Optimizing assignment into an array from various arrays - NumPy |
Python | I was optimizing a piece of code and figured out that list copying ( shallow ) was the bottleneck.Now I am curious : why is list copying so much slower than copying an array of 8-bytes ? In my opinion there should be no difference . In both cases it should be just memcpy ( dst , src , sizeof ( int64_t ) *len ( src ) ) ... | import arrayimport numpy as npimport timeitn = 100*1000lst = [ i for i in range ( n ) ] arr = array.array ( ' q ' , lst ) nmp = np.array ( arr , dtype=np.int64 ) assert ( arr.itemsize == 8 ) n_iter = 100000print ( '=== copy ( ) === ' ) print ( 'List of int : ' , timeit.timeit ( stmt='lst.copy ( ) ' , setup='from __main... | Copy performance : list vs array |
Python | For some time , Python has had Abstract Base Classes ( proposed orignally in PEP 3119 ) that , especially for container types , make it easier to write code that generalizes across custom types . For example , One of the ‘ gotchas ’ that ’ s tripped me up a few times is that str , bytes , and bytearray are all consider... | from collections.abc import Sequence , Setif isinstance ( x , Sequence ) : # Handle lists , tuples , or custom objects that behave like listselif isinstance ( x , Set ) : # Handle anything that behaves like a set from collections.abc import ByteString , Sequences = 'hello ' b = b'hello'ba = bytearray ( b'hello ' ) lst ... | How to test for sequences that are not string-like using Python 3 's standard library |
Python | I try to calculate betweenness for all nodes for the path from 2 to 6 in this simple graph.However the result is : I was wondering why the betweenness for node 5 is 0.5 while it should be 1 since the number of total shortest path is 2 and both of them include 5 and node 4 and 7 should be 0.5 | G=nx.Graph ( ) edge= [ ( 1,5 ) , ( 2,5 ) , ( 3,5 ) , ( 4,5 ) , ( 4,6 ) , ( 5,7 ) , ( 7,6 ) ] G.add_edges_from ( edge ) btw=nx.betweenness_centrality_subset ( G , [ 2 ] , [ 6 ] ) { 1 : 0.0 , 5 : 0.5 , 2 : 0.0 , 3 : 0.0 , 4 : 0.25 , 6 : 0.0 , 7 : 0.25 } | is this betweenness calculation correct ? |
Python | I have a list that looks like this : I want to keep the firstly found duplicate items in this list , based on the first item in every tuple : Is there an efficient way to do this ? | [ ( 1 , 0.3 ) , ( 3 , 0.2 ) , ( 3 , 0.15 ) , ( 1 , 0.07 ) , ( 1 , 0.02 ) , ( 2 , 0.01 ) ] [ ( 1 , 0.3 ) , ( 3 , 0.2 ) , ( 2 , 0.01 ) ] | Keep firstly found duplicate items in a list |
Python | Imagine a discrete x , y , z space : I am trying to create an iterator which will return all points which lie within a sphere of some radial distance from a point . My approach was to first look at all points within a larger cube which is guaranteed to contain all the points needed and then cull or skip points which ar... | x , y , z= ( 0,0,1 ) dist=2 # this does n't workit_0= ( ( x+xp , y+yp , z+zp ) for xp in range ( -dist , dist+1 ) for yp in range ( -dist , dist+1 ) for zp in range ( -dist , dist+1 ) if ( ( ( x-xp ) **2+ ( y-yp ) **2+ ( z-zp ) **2 ) < = dist**2+sys.float_info.epsilon ) ) for d , e , f in it_0 : # print ( d , e , f ) p... | python comprehension with multiple 'for ' clauses and single 'if ' |
Python | I am using Google OR-Tools to optimize the routing of a single vehicle over the span of a several day.I am trying to : Be able to specify the number of days over which to optimize routing.Be able to specify the start location and end location for each day.Be able to specify the start time and end time for each day.I ha... | 1 Day : Matrix = [ [ start day 1 ] , [ end day 1 ] , [ location ] , [ location ] , ... ] 2 Days : Matrix = [ [ start day 1 ] , [ end day 1 ] , [ start day 2 ] , [ end day 2 ] , [ location ] , [ location ] , ... ] 3 Days : Matrix = [ [ start day 1 ] , [ end day 1 ] , [ start day 2 ] , [ end day 2 ] , [ start day 3 ] , [... | Google OR-Tools TSP spanning multiple days with start/stop times |
Python | I have a sample csv file containsSample code convert into tsvExpecting result will beBut the result woud be | col1 '' hello \nworld '' '' the quick \njump\n \r \t brown fox '' import pandas as pddf = read_csv ( r ' a.csv ' ) df.to_csv ( 'data.tsv ' , sep='\t ' , encoding='utf-8 ' , escapechar='\n ' ) col1 '' hello \n world '' '' the quick \njump \n \r \t brown fox '' col1 '' hello \nworld '' '' the quick \njump\n \r \t brown f... | Convert csv into tsv using pandas with escapechar |
Python | https : //docs.python.org/3/using/cmdline.htmlThis is the option documentation . but it does n't provide me any useful messageI want to execute code in this way the error messageit works on Linux , but not windows . Hope you can give a full fixed command ~~~ Another question connected with this one \n problem when usin... | python -c `` def hello ( ) : \n print ( 'hello world ' ) '' PS C : \Users\Administrator > python -c `` def hello ( ) : \n print ( 'hello world ' ) '' File `` < string > '' , line 1 def hello ( ) : \n print ( 'hello world ' ) ^SyntaxError : unexpected character after line continuation character | how to use python -c on windows ? |
Python | I am succeding fiiting a function with iminuit in python but I ca n't get rid of the message even with `` print_level =-1 '' or `` print_level =0 '' .Here is the minimalist code I use : it returns : I just want it to be quiet because I fit inside a loop with ~170.000 set of data.Thank you | from iminuit import Minuitm = Minuit ( chi2 , alpha=1. , beta=0. , print_level=-1 ) creatFitsFile.py:430 : InitialParamWarning : errordef is not given . Default to 1.m = Minuit ( chi2 , alpha=1. , beta=0. , print_level=-1 ) creatFitsFile.py:430 : InitialParamWarning : Parameter alpha is floating but does not have initi... | `` print_level =-1 '' does n't remove all messages |
Python | I have the data in dataframes like below . I want to split the item into same number of rowsfrom above dataframe , I want the below as I tried several ways , but no success . | > > > dfidx a 0 3 1 5 2 4 > > > dfidx a 0 1 1 2 2 33 14 25 36 47 58 19 210 311 4 | split item to rows pandas |
Python | Given a list such as : [ 3 , 30 , 34 , 5 , 9 ] .Output : 9534330Write a program to return the largest number possibleIn my code I have used permutation here : Here n which is the length of the number of permutations is 120 because of 5 ! .Is there a better way to solve this problem ? | from itertools import permutationsx = [ 3 , 30 , 34 , 5 , 9 ] y = permutations ( x ) n = len ( y ) e = [ ] for i in y : a = map ( str , i ) e.append ( int ( `` '' .join ( i ) ) ) print `` Largest Number { } '' .format ( sorted ( e ) [ -1 ] ) | form the largest number possible in a list |
Python | I have a problem where I want to identify and remove columns in a logic matrix that are subsets of other columns . i.e . [ 1 , 0 , 1 ] is a subset of [ 1 , 1 , 1 ] ; but neither of [ 1 , 1 , 0 ] and [ 0 , 1 , 1 ] are subsets of each other . I wrote out a quick piece of code that identifies the columns that are subsets ... | import numpy as npA = np.array ( [ [ 1 , 0 , 0 , 0 , 0 , 1 ] , [ 0 , 1 , 1 , 1 , 1 , 0 ] , [ 1 , 0 , 1 , 0 , 1 , 1 ] , [ 1 , 1 , 0 , 1 , 0 , 1 ] , [ 1 , 1 , 0 , 1 , 0 , 0 ] , [ 1 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 1 , 1 , 1 , 0 ] , [ 0 , 0 , 1 , 0 , 1 , 0 ] ] ) rows , cols = A.shapecolumns = [ True ] *colsfor i in range... | 2-D Matrix : Finding and deleting columns that are subsets of other columns |
Python | I have a small dataframe , consisting of just two columns , which should have all floats in it . So , I have two fields name 'Price ' and 'Score ' . When I look at the data , it all looks like floats to me , but apparently something is a string . Is there some way to kick out these things that are strings , but look li... | df = pd.read_csv ( ' C : \\my_path\\analytics.csv ' ) print ( 'done ! ' ) modDF = df [ [ 'Price ' , 'Score ' ] ] .copy ( ) modDF = modDF [ :100 ] for i_dataset , dataset in enumerate ( datasets ) : X , y = dataset # normalize dataset for easier parameter selection X = StandardScaler ( ) .fit_transform ( X ) datasets = ... | How to force all strings to floats ? |
Python | More specifically , I want to be able to support lambda : < some_or_other_setter > , but I want to keep the code clear and to a concise . I have to validate the value , so I need a setter of some kind . I need to use lambda because I need to pass callbacks to Tkinter events . I also need to be able to modify the value ... | class Eggs ( object ) : def __init__ ( self ) : self._spam = `` self.set_spam ( 'Monster ' ) print self.get_spam ( ) spam_button.bind ( ' < Enter > ' , lambda : self.set_spam ( 'Ouch ' ) ) def set_spam ( self , spam ) : if len ( spam ) < = 32 : self._spam = spam def get_spam ( self ) : return self._spam class Eggs ( ob... | What would be the most pythonic way to make an attribute that can be used in a lambda ? |
Python | I have the following list of lists of values and I want to find the min value among all the values.I was planning to do something like : I tried this approach on a smaller example and it works : But using this on my original list Q it returns the wrong result : Why is this approach wrong and why ? | Q = [ [ 8.85008011807927 , 4.129896248976861 , 5.556804136197901 ] , [ 8.047707185696948 , 7.140707521433818 , 7.150610818529693 ] , [ 7.5326340018228555 , 7.065307672838521 , 6.862894377422498 ] ] min ( min ( Q ) ) > > > b = [ [ 2,2 ] , [ 1,9 ] ] > > > min ( b ) [ 1 , 9 ] > > > min ( min ( b ) ) 1 > > > min ( Q ) [ 7.... | Understanding python policy for finding the minimum in a list of list |
Python | I need to generate a column that starts with an initial value , and then is generated by a function that includes past values of that column . For exampleNow , I want to generate the rest of the column ' b ' by taking the minimum of the previous row and adding two . One solution would beResulting in the desired outputD... | df = pd.DataFrame ( { ' a ' : [ 1,1,5,2,7,8,16,16,16 ] } ) df [ ' b ' ] = 0df.ix [ 0 , ' b ' ] = 1df a b0 1 11 1 02 5 03 2 04 7 05 8 06 16 07 16 08 16 0 for i in range ( 1 , len ( df ) ) : df.ix [ i , ' b ' ] = df.ix [ i-1 , : ] .min ( ) + 2 a b0 1 11 1 32 5 33 2 54 7 45 8 66 16 87 16 108 16 12 | Pandas : building a column with self-referencing past values |
Python | Could someone help me understand what is going on in the following Python code ( python 3.2 ) ? I 'm really clueless here.Thank you . | import sysu = sys.stdin.readline ( ) # try entering the string `` 1 2 3 '' r = map ( lambda t : int ( t.strip ( ) ) , u.split ( ) ) print ( sum ( r ) ) # prints 6print ( sum ( r ) ) # prints 0 ? | python - same instruction , different outcome |
Python | I want to create a column df [ 'score ' ] that returns the count of values in common between a cell and a list.Input : Intended Output : Any ideas ? Thanks ! | correct_list = [ 'cats ' , 'dogs ' ] answer 0 cats , dogs , pigs1 cats , dogs 2 dogs , pigs 3 cats 4 pigs def animal_count ( dataframe ) : count = 0 for term in df [ 'answer ' ] : if term in symptom_list : df [ 'score ' ] = count + 1animal_count ( df ) correct_list = [ 'cats ' , 'dogs ' ] answer score0 cats , dogs , pi... | How can I create a column with counts between a column and a list in Pandas ? |
Python | I have the following dataframe : It looks like this : I 'd like to insert the following dictionary as the last column with index ( row ) names SRT and SRT2 .Yielding : How can I achieve that ? | import pandas as pddf = pd.DataFrame ( { 'id ' : [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' ] , 'Sample1 ' : [ -14 , -90 , -90 , -96 , -91 ] , 'Sample2 ' : [ -103,0 , -110 , -114 , -114 ] , 'Sample3 ' : [ 1,2.3,3,5,6 ] , } ) df.set_index ( 'id ' , inplace=True ) df Sample1 Sample2 Sample3ida -14 -103 1.0b -90 0 2.3c -90 -1... | How to insert dictionaries as last rows in Pandas DataFrame |
Python | After creating request from python web2py . I am receiving the following error from fine uploader '' The request signature we calculated does not match the signature you provided . Check your key and signing method . `` This is my server side code | def _sign ( key , msg ) : return hmac.new ( key , msg.encode ( `` utf-8 '' ) , hashlib.sha256 ) .digest ( ) def getV4Signature ( date_stamp , regionName , policy ) : kDate = _sign ( ( 'AWS4 ' + AWS_SECRET_KEY ) .encode ( 'utf-8 ' ) , date_stamp ) kRegion = _sign ( kDate , regionName ) kService = _sign ( kRegion , 's3 '... | Python - Fine Uploader Server Side AWS Version 4 signing request |
Python | I start with the following DataFrame : I want to get it to look like this : And I can do it , with this code : But there are so many steps here that I feel code smell , or at least something vaguely not pandas-idiomatic , as if I 'm missing the point of something in the API . Doing the equivalent for row-based indexes ... | df_1 = DataFrame ( { `` Cat1 '' : [ `` a '' , `` b '' ] , `` Vals1 '' : [ 1,2 ] , `` Vals2 '' : [ 3,4 ] } ) df df_2 = ( pd.melt ( df_1 , id_vars= [ `` Cat1 '' ] ) .T ) df_2.columns = ( pd.MultiIndex .from_tuples ( list ( zip ( df_2.loc [ `` Cat1 '' , : ] , df_2.loc [ `` variable '' , : ] ) ) , names= [ `` Cat1 '' , Non... | Pandas : Optimal way to MultiIndex columns |
Python | I have tried set signal handler with sigaction and ctypes . ( I know it is able to do with signal module in python , but I want to try it for learn . ) When I sent SIGTERM to this process , but it does not call handler that I set , only print `` Terminated '' . Why it does not invoke the handler ? I using Ubuntu 19.10 ... | import ctypesfrom ctypes import *from ctypes.util import *from os import getpidclass sigset_t ( Structure ) : __fields__ = [ ( `` __val '' , c_ulong*16 ) ] class sigval_t ( Union ) : __fields__ = [ ( `` sival_int '' , c_int ) , ( `` sival_ptr '' , c_void_p ) ] class siginfo_t ( Structure ) : __fields__ = [ ( `` si_sign... | Signal handler does not be invoked despite I have set it in python ctypes |
Python | I 've come up with the following which should be fairly close , but it 's not quite right . I am getting the following error when I try to test if the data is a weekday . AttributeError : 'str ' object has no attribute 'isoweekday'Here is my feeble code : I 'm looking for the string 'Run : ' ( it always has 2 blanks af... | offset = str ( link ) .find ( 'Run : ' ) amount = offset + 15pos = str ( link ) [ offset : amount ] if pos.isoweekday ( ) in range ( 1 , 6 ) : outF.write ( str ( link ) ) outF.write ( '\n ' ) | How to search for a substring , find the beginning and ending , and then check if that data is a weekday ? |
Python | I am trying to get speaker labels through IBM watson speech to text api.In my final output I want it to display the transcript , the confidence and the speaker labels for the entire audio . My code is below : However , the output of df is : As you can observe , I do get the transcript successfully , however , instead o... | import jsonfrom os.path import join , dirnamefrom ibm_watson import SpeechToTextV1from ibm_watson.websocket import RecognizeCallback , AudioSourceimport threadingfrom ibm_cloud_sdk_core.authenticators import IAMAuthenticatorimport pandas as pdauthenticator = IAMAuthenticator ( 'rXXXYYZZ ' ) service = SpeechToTextV1 ( a... | Speaker label/ diarization does not return in Watson Speech to Text API |
Python | Hello I have a python variable with List plus dictionary I have tried everything But I could n't get 'addr ' extracted.Help Please . | > > > print ( b [ 0 ] ) { 'peer ' : '127.0.0.1 ' , 'netmask ' : '255.0.0.0 ' , 'addr ' : '127.0.0.1 ' } -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - > > > print ( b ) [ { 'peer ' : '127.0.0.1 ' , 'netmask ' : '255.0.0.0 ' , 'addr ' : '127.0.0.1 ' } ] > > > | How to get data from list with dictionary |
Python | I need to make my code faster . The problem is very simple , but I 'm not finding a good way to make the calculation without looping through the whole DataFrame.I 've got three dataFrames : A , B and C.A and B have 3 columns each , and the following format : A ( 10 rows ) : B ( 25 rows ) : DataFrame C , on the other ha... | Canal Gerencia grad0 'ABC ' 'DEF ' 23etc ... Marca Formato grad0 'GHI ' 'JKL ' 43etc ... Marca Formato Canal Gerencia grad0 'GHI ' 'JKL ' 'ABC ' 'DEF ' -102etc ... m = 'GHI ' f = 'JKL ' c = 'ABC ' g = 'DEF'res = C [ 'grad ' ] [ C [ 'Marca ' ] ==m ] [ C [ 'Formato ' ] ==f ] [ C [ 'Canal ' ] ==c ] [ C [ 'Gerencia ' ] ==g... | Efficient calculation on a pandas dataframe |
Python | I wrote this example to show myself that __exit__ is not being run when an exception occurs : Output : That said , what is the correct way to use a with statement and catch exceptions , while making sure __exit__ is being run in the end ? Thanks ! | class A ( object ) : def __enter__ ( self ) : print ( 'enter ' ) def __exit__ ( self ) : print ( 'exit ' ) try : with A ( ) as a : raise RunTimeError ( ) except Exception as e : print ( 'except ' ) enterexcept | How to close file while using with and try..except ? |
Python | I 'm looking for a Pythonic way or more efficient way to solve this problem . I have a dictionary which has sets as values ( duplicates allowed across keys ) . Given a list I must create a dictionary which maps each category to the element using the key from the master dictionary . I 'll give an example to illustrate.M... | { `` KeyA '' : [ 'Aron ' , 'Ranom Value ' , 'Abhishek ' ] , `` KeyB '' : [ 'Ball ' , 'Foo ' , 'Bar ' , 'Badge ' , 'Dog ' ] , `` KeyZ '' : [ 'Random Value ' , 'Foo ' , 'Bar ' ] } [ 'Foo ' , 'Bar ' , 'Dog ' , 'Aron ' ] { `` KeyA '' : [ 'Aron ' ] , `` KeyB '' : [ 'Bar ' , 'Foo ' , 'Dog ' ] , `` KeyZ '' : [ 'Foo ' , 'Bar '... | Pythonic way to group a list using a dictionary that has lists as values |
Python | This code works as expected . Output : Code : And this code does n't . Output : Code : Why does the time function seem to skip every second print statement if it is lower than 0.25 ? | Loading Loading.Loading..Loading ... done = Falsecount = 0while not done : print ' { 0 } \r'.format ( `` Loading '' ) , time.sleep ( 0.25 ) print ' { 0 } \r'.format ( `` Loading . `` ) , time.sleep ( 0.25 ) print ' { 0 } \r'.format ( `` Loading.. '' ) , time.sleep ( 0.25 ) print ' { 0 } \r'.format ( `` Loading ... '' )... | Why time ( ) below 0.25 skips animation in Python ? |
Python | I want to merge two datasets that are indexed by time and id . The problem is , the time is slightly different in each dataset . In one dataset , the time ( Monthly ) is mid-month , so the 15th of every month . In the other dataset , it is the last business day . This should still be a one-to-one match , but the dates ... | dt = pd.date_range ( ' 1/1/2011 ' , '12/31/2011 ' , freq='D ' ) dt = dt [ dt.day == 15 ] lst = [ 1,2,3 ] idx = pd.MultiIndex.from_product ( [ dt , lst ] , names= [ 'date ' , 'id ' ] ) df = pd.DataFrame ( np.random.randn ( len ( idx ) ) , index=idx ) df.head ( ) 0date id2011-01-15 1 -0.598584 2 -0.484455 3 -2.0449122011... | Shift time in multi-index to merge |
Python | So I get some input in python that I need to parse using regexps.At the moment I 'm using something like this : Now usually I love python because its nice and succinct . But this feels verbose . I 'd expect to be able to do something like this : Am I missing something , or is the first form as neat as I 'm going to get... | matchOK = re.compile ( r'^OK\s+ ( \w+ ) \s+ ( \w+ ) $ ' ) matchFailed = re.compile ( r'^FAILED\s ( \w+ ) $ ' ) # ... . a bunch more regexpsfor l in big_input : match = matchOK.search ( l ) if match : # do something with match continue match = matchFailed.search ( l ) if match : # do something with match continue # ... ... | How can I handle several regexp cases neatly in python |
Python | I am studying algorithms in Python and solving a question that is : Let x ( k ) be a recursively defined string with base case x ( 1 ) = `` 123 '' and x ( k ) is `` 1 '' + x ( k-1 ) + `` 2 '' + x ( k-1 ) + `` 3 '' . Given three positiveintegers k , s , and t , find the substring x ( k ) [ s : t ] .For example , if k = ... | def generate_string ( k ) : if k == 1 : return `` 123 '' part = generate_string ( k -1 ) return ( `` 1 '' + part + `` 2 '' + part + `` 3 '' ) print ( generate_string ( k ) [ s , t ] ) | Find the substring avoiding the use of recursive function |
Python | I 'm having a nested JSON document and want to update elements in it . Below is the JSON file.Have validated this JSON via online formatting multiple times as well.In this , I want to access 'values ' and add element name : ABC and name : CBA in the subsequent entries.Now with below code am getting a dictionary data bu... | { `` j1 '' : [ { `` URL '' : `` http : //localhost/ '' , `` Data '' : `` { \ '' dump\ '' : [ { values : [ { time:1586826385724 , val:5.12 } , { time:1587576460460 , val:3.312 } ] } ] } '' } ] } { values : [ { name : 'ABC ' , time:1586826385724 , val:5.12 } , { name : 'CBA ' , time:1587576460460 , val:3.312 } ] } import... | Traverse and Accessing inner elements in JSON |
Python | The default __init__ method of class c is called on obj creation , which internally calls the __init__ of only class b.As per my understanding , if I inherit from 2 class , my derived class object should have variables from both class ( unless they are private to those classes ) .My Question : Am I wrong in expecting m... | In [ 5 ] : class a ( object ) : ... : def __init__ ( self ) : ... : print `` In class a '' ... : self.a = 1 ... : In [ 6 ] : class b ( object ) : ... : def __init__ ( self ) : ... : print `` In class b '' ... : self.b = 2 ... : ... : In [ 7 ] : class c ( b , a ) : ... : pass ... : In [ 8 ] : c.mro ( ) Out [ 8 ] : [ < c... | Behaviour of Mutlple inheritance in python |
Python | Is there any Python function for the `` in '' operator like what we have for operator.lt , operator.gt , ..I wa n't to use this function to do something like : | operator.in ( 5 , [ 1,2,3,4,5,6 ] ) > > Trueoperator.in ( 10 , [ 1,2,3,4,5,6 ] ) > > False | In Python is there a function for the `` in '' operator |
Python | I am having 3 dictionaries in my python code : self.new_port_dict = { } # Dictionary to store the new portsfrom curr_hostself.old_port_dict = { } # Dictionary to store the old ports from old_hostself.results_ports_dict = { } # Holds the result of changed/newly added portsThe script needs to compare what port changed , ... | def comp_ports ( self , filename ) : try : f = open ( filename ) self.prev_report = pickle.load ( f ) # NmapReport for s in self.prev_report.hosts : self.old_port_dict [ s.address ] = set ( ) for x in s.get_open_ports ( ) : self.old_port_dict [ s.address ] .add ( x ) for s in self.report.hosts : self.new_port_dict [ s.... | How to compare dictionaries and see what changed ? |
Python | In Python , I can overload an object 's __add__ method ( or other double-underscore aka `` dunder '' methods ) . This allows me to define custom behavior for my objects when using Python operators.Is it possible to know , from within the dunder method , if the method was called via + or via __add__ ? For example , supp... | class MyAdder ( object ) : def __add__ ( self , other ) : print method_how_created ( ) return 0MyAdder ( ) + 7 # prints `` + '' , returns 0MyAdder ( ) .__add__ ( 7 ) # prints `` __add__ '' , returns 0 | Know if + or __add__ called on an object |
Python | I have written the following code in two different ways . I am trying to find the `` correct pythonic '' way of doing it . I will explain the reasons for both.First way , EAFP . This one uses pythons EAFP priciple , but causes some code duplication.Second way , LBYL . LBYL is not exactly considered pythonic , but it re... | try : my_dict [ 'foo ' ] [ 'bar ' ] = some_varexcept KeyError : my_dict [ 'foo ' ] = { } my_dict [ 'foo ' ] [ 'bar ' ] = some_var if 'foo ' not in my_dict : my_dict [ 'foo ' ] = { } my_dict [ 'foo ' ] [ 'bar ' ] = some_var | Correct way to edit dictionary value python |
Python | I have a pandas dataframe with two columns A , B as below.I want a vectorized solution for creating a new column C where C [ i ] = C [ i-1 ] - A [ i ] + B [ i ] .Here is the solution using for-loops : ... which does the job.But since loops are slow in comparison to vectorized calculations , I want a vectorized solution... | df = pd.DataFrame ( data= { ' A ' : [ 10 , 2 , 3 , 4 , 5 , 6 ] , ' B ' : [ 0 , 1 , 2 , 3 , 4 , 5 ] } ) > > > df A B 0 10 0 1 2 1 2 3 2 3 4 3 4 5 4 5 6 5 df [ ' C ' ] = df [ ' A ' ] for i in range ( 1 , len ( df ) ) : df [ ' C ' ] [ i ] = df [ ' C ' ] [ i-1 ] - df [ ' A ' ] [ i ] + df [ ' B ' ] [ i ] > > > df A B C0 10 ... | Vectorized calculation of a column 's value based on a previous value of the same column ? |
Python | From the docs relative to async for syntax in Python 3.5 , I gathered that it was introduced to iterate over an awaitable iterator.There is something I do n't get in the semantic equivalent that follow the description though : What is the line iter = type ( iter ) .__aiter__ ( iter ) doing ? Why is it necessary ? | iter = ( ITER ) iter = type ( iter ) .__aiter__ ( iter ) running = Truewhile running : try : TARGET = await type ( iter ) .__anext__ ( iter ) except StopAsyncIteration : running = False else : BLOCKelse : BLOCK2 | Semantic equivalent of async for |
Python | I have been trying to teach myself Python and am currently on regular expressions . The instructional text I have been using seems to be aimed at teaching Perl or some other language that is not Python , so I have had to adapt the expressions a bit to fit Python . I 'm not very experienced , however , and I 've hit a s... | \ $ [ 0-9 ] + ( \. [ 0-9 ] [ 0-9 ] ) ? import reinputstring = `` $ 500.01 '' result = re.findall ( r'\ $ [ 0-9 ] + ( \. [ 0-9 ] [ 0-9 ] ) ? ' , inputstring ) if result : print ( result ) else : print ( `` No match . '' ) .01 \ $ [ 0-9 ] +\ . [ 0-9 ] [ 0-9 ] $ 500.01 | Python regex returns a part of the match when used with re.findall |
Python | Is there a simple way to obtain the hour of the year from a datetime ? Expected output : dt_hour = 48It would be nice as well to obtain minutes_of_year and seconds_of_year | dt = datetime ( 2019 , 1 , 3 , 00 , 00 , 00 ) # 03/01/2019 00:00dt_hour = dt.hour_of_year ( ) # should be something like that | Get hour of year from a Datetime |
Python | So I have been trying to multi-thread some internet connections in python . I have been using the multiprocessing module so I can get around the `` Global Interpreter Lock '' . But it seems that the system only gives one open connection port to python , Or at least it only allows one connection to happen at once . Here... | from multiprocessing import Process , Queueimport urllibimport random # Generate 10,000 random urls to test and put them in the queuequeue = Queue ( ) for each in range ( 10000 ) : rand_num = random.randint ( 1000,10000 ) url = ( 'http : //www . ' + str ( rand_num ) + '.com ' ) queue.put ( url ) # Main funtion for chec... | How many network ports does Linux allow python to use ? |
Python | Can I catch and dump an exception ( and the corresponding stacktrace ) that would make the program crash without doing something like : Sometime a external library crashes , and I 'd like to react to Python dying and log the reasons it does so . I do n't want to prevent the Exception from crashing the program , I just ... | try : # whole programexcept Execption as e : dump ( e ) raise signals.register ( 'dying ' , callback ) def callback ( context ) : # dumping the exception and # stack trace from here | Is there a way to react to an Exception raising to the top of the program without try/except in Python ? |
Python | I 'm messing around with some plot styles and ran into a curiosity . I have a plot with twinx ( ) to produce ticks on the right-hand side as well as the left . I want to stagger some ticks , some going farther out that others.I can add padding to any tick on any axes and push out the text via ax.yaxis.get_major_ticks (... | import matplotlib.pyplot as pltimport matplotlib as mplimport numpy as npt = np.linspace ( 0,5 ) x = np.exp ( -t ) *np.sin ( 2*t ) fig , ax1 = plt.subplots ( ) ax1.plot ( t , x , alpha=0.0 ) ax2 = ax1.twinx ( ) ax2.plot ( t , x , alpha=1.0 ) ax1.set_xticks ( [ 0,1,2 ] ) ax1.set_yticks ( [ 0.1 , 0.2 ] ) ax2.set_yticks (... | set_markersize not working for right side axis |
Python | I 'm working my way through Gmail access using imaplib and came across : I just wish to know what : does in front of the `` response = '' . I would google it , but I have no idea what I 'd even ask to find an answer for that : ( .Thanks . | # Count the unread emailsstatus , response = imap_server.status ( 'INBOX ' , `` ( UNSEEN ) '' ) unreadcount = int ( response [ 0 ] .split ( ) [ 2 ] .strip ( ' ) . , ] ' ) ) print unreadcount status , | Understanding some Python code |
Python | I have a df that I am grouping by two columns . I want to count each group sequentially . The code below counts each row within a group sequentially . This seems easier than I think but ca n't figure it out . Anticipated result : | df = pd.DataFrame ( { 'Key ' : [ '10003 ' , '10009 ' , '10009 ' , '10009 ' , '10009 ' , '10034 ' , '10034 ' , '10034 ' ] , 'Date1 ' : [ 20120506 , 20120506 , 20120506 , 20120506 , 20120620 , 20120206 , 20120206 , 20120405 ] , 'Date2 ' : [ 20120528 , 20120507 , 20120615 , 20120629 , 20120621 , 20120305 , 20120506 , 2012... | Count each group sequentially pandas |
Python | I have a list of objects named items . Each object has a property state and a property children , which is another list of objects . And each child object has also a property named state . What I want to know is if every item and their children are in the states happy or cheerful.I did this with all ( only analysing th... | if all ( item.state in [ 'happy ' , 'cheerful ' ] for item in items ) : pass | Is it possible to nest the all function ? |
Python | I saw some code yesterday in this question that I had not seen before , this line in particular : So as this loop runs , the elements from possible [ num ] are assigned to the list xyz at position num . I was really confused by this so I did some tests , and here is some equivalent code that is a little more explicit :... | for xyz [ num ] in possible [ num ] : ... for value in possible [ num ] : xyz [ num ] = value ... > > > import string > > > rot13 = [ None ] *26 > > > for i , rot13 [ i % 26 ] in enumerate ( string.ascii_lowercase , 13 ) : pass ... > > > `` .join ( rot13 ) 'nopqrstuvwxyzabcdefghijklm ' > > > rot13_dict = { } > > > for ... | Any good use for list/dict assignment during for loop ? |
Python | I have a pandas ( version 0.25.3 ) DataFrame containing a datetime64 column . I 'd like to calculate the mean of each column.Calculating the mean of individual columns is pretty much instantaneous.However , when I use the DataFrame 's .mean ( ) method , it takes a really long time.It is n't clear to me where the perfor... | import numpy as npimport pandas as pdn = 1000000df = pd.DataFrame ( { `` x '' : np.random.normal ( 0.0 , 1.0 , n ) , `` d '' : pd.date_range ( pd.datetime.today ( ) , periods=n , freq= '' 1H '' ) .tolist ( ) } ) df [ `` x '' ] .mean ( ) # # 1000 loops , best of 3 : 1.35 ms per loopdf [ `` d '' ] .mean ( ) # # 100 loops... | How to avoid poor performance of pandas mean ( ) with datetime columns |
Python | I have pictures of apple slices that have been soaked in an iodine solution . The goal is to segment the apples into individual regions of interest and evaluate the starch level of each one . This is for a school project so my goal is to test different methods of segmentation and objectively find the best solution whet... | import cv2import numpy as np # Load imageimage = cv2.imread ( 'ApplePic.jpg ' ) # Set minimum and max HSV values to displaylower = np.array ( [ 0 , 0 , 0 ] ) upper = np.array ( [ 105 , 200 , 255 ] ) # Create HSV Image and threshold into a range.hsv = cv2.cvtColor ( image , cv2.COLOR_BGR2HSV ) mask = cv2.inRange ( hsv ,... | Looking for different methods of image segmentation for pictures of apples |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.