lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I have a 2d array , and I have some numbers to add to some cells . I want to vectorize the operation in order to save time . The problem is when I need to add several numbers to the same cell . In this case , the vectorized code only adds the last . ' a ' is my array , ' x ' and ' y ' are the coordinates of the cells I... | import numpy as npa=np.zeros ( ( 4,4 ) ) x= [ 1,2,1 ] y= [ 0,1,0 ] z= [ 2,3,1 ] a [ x , y ] +=zprint ( a ) [ [ 0 . 0 . 0 . 0 . ] [ 3 . 0 . 0 . 0 . ] [ 0 . 3 . 0 . 0 . ] [ 0 . 0 . 0 . 0 . ] ] [ [ 0 . 0 . 0 . 0 . ] [ 1 . 0 . 0 . 0 . ] [ 0 . 3 . 0 . 0 . ] [ 0 . 0 . 0 . 0 . ] ] | How to vectorize increments in Python |
Python | I have got a chunk of code likewhere a and b are arrays of the same length , a is given ( and big ) , func is some function that has a lot of local variables but does not use any global variables . I would like to distribute computations of func across several CPUs . Presumably I need to use multiprocessing module , bu... | for i in range ( 0 , len ( a ) ) b [ i ] = func ( a [ i ] ) | Parallelizing multiplication of vectors-like computation in python |
Python | When I changed to : I found the second code is much more efficient , why ? bench mark it , and in my situation ranks is an numpy array of integer . The difference is much more.output : | for i in range ( 0 , 100 ) : rank = ranks [ i ] if rank ! = 0 : pass for i in range ( 0 , 100 ) : rank = ranks [ i ] if rank : pass import numpy as npimport timeN = 1000000ranks = np.random.random_integers ( 0 , 10 , N ) start = time.time ( ) for i in range ( 0 , N ) : rank = ranks [ i ] if rank ! = 0 : passprint time.... | in python why if rank : is faster than if rank ! = 0 : |
Python | Recently I ran into cosmologicon 's pywats and now try to understand part about fun with iterators : Ok , sorted ( a ) returns a list and sorted ( a ) == sorted ( a ) becomes just a two lists comparision . But reversed ( a ) returns reversed object . So why these reversed objects are different ? And id 's comparision m... | > > > a = 2 , 1 , 3 > > > sorted ( a ) == sorted ( a ) True > > > reversed ( a ) == reversed ( a ) False > > > id ( reversed ( a ) ) == id ( reversed ( a ) ) True | Understanding iterable types in comparisons |
Python | While looking for a pythonic way to rotate a matrix , I came across this answer . However there is no explanation attached to it . I copied the snippet here : How does it work ? | rotated = zip ( *original [ : :-1 ] ) | How does this code snippet rotating a matrix work ? |
Python | Is there any bulid-in function in python/numpy to convert an array = [ 1 , 3 , 1 , 2 ] to something like this : | array = [ [ 0 , 1 , 0 , 0 ] , [ 0 , 0 , 0 , 1 ] , [ 0 , 1 , 0 , 0 ] , [ 0 , 0 , 1 , 0 ] ] | How to covert 1d array to Logical matrix |
Python | I have time series data in the following format , where a value indicates an accumulated amount since the past recording . What I want to do is `` spread '' that accumulated amount over the past periods containing NaN so that this input : Becomes this output : Is there an idiomatic Pandas way to do this rather than jus... | s = pd.Series ( [ 0 , 0 , np.nan , np.nan , 75 , np.nan , np.nan , np.nan , np.nan , 50 ] , pd.date_range ( start= '' Jan 1 2016 '' , end= '' Jan 10 2016 '' , freq='D ' ) ) 2016-01-01 0.02016-01-02 0.02016-01-03 NaN2016-01-04 NaN2016-01-05 75.02016-01-06 NaN2016-01-07 NaN2016-01-08 NaN2016-01-09 NaN2016-01-10 50.0 2016... | Pandas idiomatic way to custom fillna |
Python | I 'm trying to create a recursive generator in Python , but I 'm doing something wrong . Here 's a minimal example . I would expect the function f ( ) to return an iterable that would give me all the positive numbers > = n.Why is the iteration stopping after the first number ? | > > > def f ( n ) : ... yield n ... if n > 0 : ... f ( n-1 ) ... > > > [ i for i in f ( 30 ) ] [ 30 ] | Why Recursive Generator does n't work in Python 3.3 ? |
Python | Given the following simple regular expression which goal is to capture the text between quotes characters : When the input is something like : The capturing group ( 1 ) has the following : I expected the group ( 1 ) to have text only ( without the quotes ) . Could somebody explain what 's going on and why the regular e... | regexp = ' '' ? ( .+ ) '' ? ' `` text '' text '' regexp = ' '' ? ( [ ^ '' ] + ) '' ? ' | Strange behavior of capturing group in regular expression |
Python | I wrote some small code for controlling multiple compute engine on google cloud platform . The whole file is here in github.The part causes problem is gcloud compute ssh in the followingThis part is for uploading the same file ( usually .zip ) to all instances with same tag . However doing it on my local computer will ... | def upload_file ( self , projectname ) : var = raw_input ( `` Upload file with name : `` + projectname + `` will remove all file and directory with same name in the instance . Are you sure ? ( y/n ) '' ) if var.lower ( ) .strip ( ) ! = `` y '' : print `` Abort uploading . '' return is_zip = False if projectname.split (... | How to avoid gcloud compute alerting store the key in cache |
Python | I 'm reading a file ( while doing some expensive logic ) that I will need to iterate several times in different functions , so I really want to read and parse the file only once.The parsing function parses the file and returns an itertools.groupby object.I thought about doing the following : However , itertools.tee see... | def parse_file ( ) : ... return itertools.groupby ( lines , key=keyfunc ) csv_file_content = read_csv_file ( ) file_content_1 , file_content_2 = itertools.tee ( csv_file_content , 2 ) foo ( file_content_1 ) bar ( file_content_2 ) from itertools import groupby , teeli = [ { 'name ' : ' a ' , 'id ' : 1 } , { 'name ' : ' ... | Using itertools.tee to duplicate a nested iterator ( ie itertools.groupby ) |
Python | I am trying to add dictionaries which have a key from each element from the list and value ( s ) from one following element from the list and a count for the number of times it follows it , in dictionary format . For example , if we have the list of words , [ 'The ' , 'cat ' , 'chased ' , 'the ' , 'dog ' ] and if the k... | line = [ 'The ' , 'cat ' , 'chased ' , 'the ' , 'dog ' ] output = { } for i , item in enumerate ( line ) : print ( i , item , len ( line ) ) if i ! = len ( line ) - 1 : output [ item ] = line [ i+1 ] =iprint ( output ) { 'The ' : 'cat ' , 'chased ' : 'the ' , 'the ' : 'dog ' , 'cat ' : 'chased ' } | Making a dictionary for value in a dictionary in Python |
Python | Using pandas v1.0.1 and numpy 1.18.1 , I want to calculate the rolling mean and std with different window sizes on a time series . In the data I am working with , the values can be constant for some subsequent points such that - depending on the window size - the rolling mean might be equal to all the values in the win... | for window in [ 3,5 ] : values = [ 1234.0 , 4567.0 , 6800.0 , 6810.0 , 6821.0 , 6820.0 , 6820.0 , 6820.0 , 6820.0 , 6820.0 , 6820.0 ] df = pd.DataFrame ( values , columns= [ 'values ' ] ) df.loc [ : , 'mean ' ] = df.rolling ( window , min_periods=1 ) .mean ( ) df.loc [ : , 'std ' ] = df.rolling ( window , min_periods=1... | Pandas rolling std yields inconsistent results and differs from values.std |
Python | I am trying out the list comprehensions . But I got stuck when I tried to write a list comprehension for the following code.output for this is : Is it even possible to write a list comprehension for this code ? if it is how would you write it ? | a = [ ' x ' , ' y ' , ' z ' ] result = [ ] for i in a : for j in range ( 1,5 ) : s = `` for k in range ( j ) : s = s + i result.append ( s ) result [ ' x ' , 'xx ' , 'xxx ' , 'xxxx ' , ' y ' , 'yy ' , 'yyy ' , 'yyyy ' , ' z ' , 'zz ' , 'zzz ' , 'zzzz ' ] | List comprehension for multiplying each string in a list by numbers from given range |
Python | I discovered a slightly strange corner of Python I was hoping to get some help understanding . Suppose I have a class B that I want to attach as a method for class A. I can do : When I call a.B ( ) , in the B.__init__ I get a self object for a new B instance.Now suppose I want to capture the actual value of the a insta... | class A : def __init__ ( self ) : print ( `` a self is % s `` % self ) class B : def __init__ ( self ) : print ( `` b self is % s `` % self ) setattr ( A , `` B '' , B ) a = A ( ) a.B ( ) class A : def __init__ ( self ) : print ( `` a self is % s `` % self ) class B : def __init__ ( self , a_instance ) : print ( `` b s... | Attaching class as method |
Python | I would like to slice a dataframe to return rows where element x=0 appears consecutively at least n=3 times , and then dropping the first i=2 instances in each mini-sequenceis there an efficient way of achieving in pandas , and if not , using numpy or scipy ? Example 1Desired output : Example 2x=0 ( element of interest... | import pandas as pdimport numpy as np df=pd.DataFrame ( { ' A ' : [ 0,1,0,0,1,1,0,0,0,0,1,1,0,0,0,1,1 ] , ' B ' : np.random.randn ( 17 ) } ) A B0 0 0.7489581 1 0.2547302 0 0.6296093 0 0.2727384 1 -1.8859065 1 1.2063716 0 -0.3324717 0 0.2175538 0 0.7689869 0 -1.60723610 1 1.61365011 1 -1.09689212 0 -0.43576213 0 0.13128... | slice pandas df based on n consecutive instances of element |
Python | I 'm quite new at TensorFlow . I 'm using TF 1.8 for a 'simple ' linear regression.The output of the exercise is the set of linear weights that best fit the data , rather than a prediction model . So I would like to track and log the current minimum loss during training , along with the corresponding value of the weigh... | tf.logging.set_verbosity ( tf.logging.INFO ) model = tf.estimator.LinearRegressor ( feature_columns = make_feature_cols ( ) , model_dir = TRAINING_OUTDIR ) # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- vlogger = tf.train.LoggingTensorHook ( { `` loss '' : ? ? ? } , every_n_iter=10 ) trainHooks = [... | Can I log training loss via a hook with a LinearRegressor ? |
Python | To better understand Python 's generator I 'm trying to implement facilities in the itertools module , and get into trouble with izip : My code uses the ERROR line , and the reference implementation ( given in the manual ) uses the OK line , not considering other tiny differences . With this snippet : My code outputs :... | def izip ( *iterables ) : its = tuple ( iter ( it ) for it in iterables ) while True : yield tuple ( next ( it ) for it in its ) # ERROR # yield tuple ( map ( next , its ) ) # OK for x in izip ( [ 1 , 2 , 3 ] , ( 4 , 5 ) ) : print x ( 1 , 4 ) ( 2 , 5 ) ( 3 , ) ( ) ( ) ... # indefinite ( ) ( 1 , 4 ) ( 2 , 5 ) | Why does this implementation of izip ( ) not work ? |
Python | So I 'm taking a programming course in high school , right now and I am making a program of a game that the teacher assigned for all of us make . The game is called `` game of sticks '' ( if you would like a better run down on how the game works skip about half way through this video https : //www.youtube.com/watch ? v... | pl1 = input ( `` Player 1 , what is your username ? '' ) # player 1pl2 = input ( `` Player 2 , what is your username ? '' ) # player 2turnsa = 0 # player1 turnsturnsb = 0 # player2 turnsx = 15 # number of stickswhichplayer = 1 while ( x ! = 1 ) : while ( whichplayer == 1 ) : P1 = int ( input ( pl1 + ' , choose an amoun... | Python 3 need help in a school project |
Python | I 'm trying to use SQLAlchemy to write a query like this : My data table has 3 columns , parent_id , date_time and value.I 've spend few hours already and there 's no way I can get it to work exactly like above.The closest I 've got ( at least semantically it make sense ) is : But its not working , it 's not possible t... | SELECT hour , avg ( value ) from generate_series ( '2019-10-01T00:00:00 ' : :timestamp , '2019-10-01T23:00:00 ' : :timestamp , ' 0 days 3600.000000 seconds ' : :interval ) AS hourleft outer join ( select * from data where parent_id=10 and date_time > = '2019-10-01T00:00:00 ' : :timestamp and date_time < '2019-10-02T00:... | How to join subquery results to function results |
Python | I 've been working extensively with dates in python/django . In order to solve various use-cases I 've been blindly trying a variety of different approaches until one of them worked , without learning the logic behind how the various functions work.Now it 's crunch time . I 'd like to ask a couple of questions regardin... | > > > generate_a_datetime ( ) datetime.datetime ( 2015 , 12 , 2 , 0 , 0 , tzinfo= < DstTzInfo 'Canada/Eastern ' LMT-1 day , 18:42:00 STD > ) > > > > > > from django.utils import timezone > > > import pytz > > > tz = pytz.timezone ( 'Canada/Eastern ' ) > > > now_unaware = datetime.datetime.now ( ) > > > now_aware_with_d... | Django/python - dispelling confusion regarding dates and timezone-awareness |
Python | Why exactly isprinted by the following code ? In particular : Why is C.__init__ ( ) not printed ? Why is C.__init__ ( ) printed if I put super ( ) .__init__ ( ) instead of A.__init__ ( self ) ? | A.__init__ ( ) B.__init__ ( ) D.__init__ ( ) # ! /usr/bin/env python3class A ( object ) : def __init__ ( self ) : super ( A , self ) .__init__ ( ) print ( `` A.__init__ ( ) '' ) class B ( A ) : def __init__ ( self ) : A.__init__ ( self ) print ( `` B.__init__ ( ) '' ) class C ( A ) : def __init__ ( self ) : A.__init__ ... | Why is an __init__ skipped when doing Base.__init__ ( self ) in multiple inheritance instead of super ( ) .__init__ ( ) ? |
Python | I am making a library that deals with Python modules . Without getting into details , I need a list of the common Python module extensions.Obviously , I want .py , but I 'd also like to include ones such as .pyw , .pyd , etc . In other words , I want anything that you can import.Is there a tool in the standard library ... | extensions = [ '.py ' , '.pyw ' , ... ] | Is there an easy way to get all common module extensions ? |
Python | I 've currently got a list of tuples ( though I control creation of the list and tuples , so they could be altered in type if needed ) . Each tuple has a start and end integer and a string with an ID for that range 's source . What I 'm trying to do is identify all of the overlapping ranges within the tuples.Currently ... | a = [ ( 0 , 98 , '122 : R ' ) , ( 100 , 210 , '124 : R ' ) , ( 180 , 398 , '125 : R ' ) , ( 200 , 298 , '123 : R ' ) ] highNum = 0highNumItem = `` for item in a : if item [ 0 ] < highNum : print ( highNumItem + ' overlaps ' + item [ 2 ] ) if item [ 1 ] > highNum : highNum = item [ 1 ] highNumItem = item [ 2 ] # 124 : R... | Identify all overlapping tuples in list |
Python | Lets say I want to use gcc from the command line in order to compile a C extension of Python . I 'd structure the call something like this : I noticed that the -I , -L , and -l options are absolutely necessary , or else you will get an error that looks something like this . These commands tell gcc where to look for the... | gcc -o applesauce.pyd -I C : /Python35/include -L C : /Python35/libs -l python35 applesauce.c from subprocess import callimport sysfilename = applesauce.cinclude_directory = os.path.join ( sys.exec_prefix , 'include ' ) libs_directory = os.path.join ( sys.exec_prefix , 'libs ' ) call ( [ 'gcc ' , ... , '-I ' , include_... | Return the include and runtime lib directories from within Python |
Python | I have data in pandas dataframe with 1 minute time step . This data is not recorded continuously , now I would like to split all my data into separate event based on the condition below : If there is continuous data recorded for 5min or more then only it is considered as a event and for such event data need to extracte... | Date X Event2017-06-06 01:08:00 0.019 12017-06-06 01:09:00 0.005 12017-06-06 01:10:00 0.03 12017-06-06 01:11:00 0.005 12017-06-06 01:12:00 0.003 12017-06-06 01:13:00 0.001 12017-06-06 01:14:00 0.039 12017-06-06 01:15:00 0.003 12017-06-06 01:17:00 0.001 nan2017-06-06 01:25:00 0.006 nan2017-06-06 01:26:00 0.006 nan2017-0... | Calculating event based on the continuous timestep |
Python | I 'm attempting to make a short program that will return the factorial of a number , which works fine . The only problem I am having is getting the program to end if the user inputs a non-integer value . | num = input ( `` input your number to be factorialised here ! : `` ) try : num1 = int ( num ) except ValueError : print ( `` That 's not a number ! `` ) if num1 < 0 : print ( `` You ca n't factorialise a negative number '' ) elif num1 == 0 : print ( `` the factorial of 0 is 1 '' ) else : for i in range ( 1 , num1+1 ) :... | ending a program early , not in a loop ? |
Python | I have a pandas dataframe with name of variables , the values for each and the count ( which shows the frequency of that row ) : I want to use count to get an output like this : What is the best way to do that ? | df = pd.DataFrame ( { 'var ' : [ ' A ' , ' B ' , ' C ' ] , 'value ' : [ 10 , 20 , 30 ] , 'count ' : [ 1,2,3 ] } ) var value countA 10 1B 20 2C 30 3 var valueA 10B 20B 20C 30C 30C 30 | Groupby in Reverse |
Python | Can anyone explain me the output of following python code : Testing the function | from theano import tensor as Tfrom theano import function , shareda , b = T.dmatrices ( ' a ' , ' b ' ) diff = a - babs_diff = abs ( diff ) diff_squared = diff ** 2f = function ( [ a , b ] , [ diff , abs_diff , diff_squared ] ) print f ( [ [ 1 , 1 ] , [ 1 , 1 ] ] , [ [ 0 , 1 ] , [ 2 , 3 ] ] ) print f ( [ [ 1,1 ] , [ 1,... | Neural Networks : Understanding theano Library |
Python | I have a dataframe like this : Further , I have a variable max_sum = 10.I want to assign a group to each row ( i ) based on the value in keys and ( ii ) the max_sum which should not be exceeded per group.My expected outcome looks like this : So , the first two values in the a group ( 1 and 5 ) sum up to 6 which is less... | df = pd.DataFrame ( { 'keys ' : list ( 'aaaabbbbccccc ' ) , 'values ' : [ 1 , 5 , 6 , 8 , 2 , 4 , 7 , 7 , 1 , 1 , 1 , 1 , 5 ] } ) keys values0 a 11 a 52 a 63 a 84 b 25 b 46 b 77 b 78 c 19 c 110 c 111 c 112 c 5 keys values group0 a 1 11 a 5 12 a 6 23 a 8 34 b 2 45 b 4 46 b 7 57 b 7 68 c 1 79 c 1 710 c 1 711 c 1 712 c 5 ... | How to assign groups based on a maximum sum ? |
Python | I have implemented a function in R to estimate the Gaussian Process parameters of a basic sin function . Unfortunately the project has to be made in Python and I have been trying to reproduce the behavior of R library 's hetGP in python using SKlearn but I have a hard time mapping the former to the later.My understandi... | library ( hetGP ) set.seed ( 123 ) nvar < - 2n < - 400r < - 1f < - function ( x ) sin ( sum ( x ) ) true_C < - matrix ( 1/8 * ( 3 + 2 * cos ( 2 ) - cos ( 4 ) ) , nrow = 2 , ncol = 2 ) design < - matrix ( runif ( nvar*n ) , ncol = nvar ) response < - apply ( design , 1 , f ) model < - mleHomGP ( design , response , lowe... | Reproducing R 's gaussian process maximum likelihood regression in Python |
Python | I have an `` interface '' that will be implemented by client code : run should in general return a docutils node but because the far far mostcommon case is plain text , the caller allows run to return a string , which will bechecked using type ( ) and turned into a node.However , the way I understand `` Pythonic '' , t... | class Runner : def run ( self ) : pass def run_str ( self ) : passdef run_node ( self ) : return make_node ( self.run_str ( ) ) | How can I balance `` Pythonic '' and `` convenient '' in this case ? |
Python | Input to pd.read_clipboard ( ) Code : Output : Questions : Why that � in the last row ? How to modify more than 1 column in 1 line ? Python Version : 2.7 , Pandas : 0.19 , IPython : 4 | Ratanhia ,30c x2 , 200c x2Aloe ,30c x2 , 200c x2Nitric Acid ,30c x2 , 200c x 2Sedum Acre ,200c x2 , 30c x2Paeonia ,200c x2 , 30c x2Sulphur ,200c x2 , 30c x2Hamamelis ,30c x1 , 200c x1Aesculus ,30c x1 , 200c x1 import pandas as pddf = pd.read_clipboard ( header=None , sep= ' , ' ) df.columns = [ 'Medicine ' , 'power... | Error in parsing , update multiple columns in 1 line |
Python | I have three arrays called RowIndex , ColIndex and Entry in numpy . Essentially , this is a subset of entries from a matrix with the row indexes , column indexes , and value of that entry in these three variables respectively . I have two numpy 2D arrays ( matrices ) U and M. Let alpha and beta be two given constants .... | i=RowIndex [ 0 ] , j=ColIndex [ 0 ] , value = Entry [ 0 ] i=RowIndex [ 1 ] , j=ColIndex [ 1 ] , value = Entry [ 1 ] for iter in np.arange ( length ( RowIndex ) ) : i = RowIndex [ iter ] j = ColIndex [ iter ] value = Entry [ iter ] e = value - np.dot ( U [ i , : ] , M [ : ,j ] ) OldUi = U [ i , : ] OldMj = M [ : ,j ] U ... | Is there a faster way to do this pseudo code efficiently in python numpy ? |
Python | I have been playing with Python these days , and I realize some interesting way how Python assign id ( address ) to new instance ( int and list ) . For example , if I keep call id function with a number ( or two different number ) , it return the same result . e.g.Also when I declare the variable first and then call id... | > > > id ( 12345 ) 4298287048 > > > id ( 12345 ) 4298287048 > > > id ( 12345 ) 4298287048 > > > id ( 12342 ) # different number here , yet still same id4298287048 > > > x = [ ] ; id ( x ) 4301901696 > > > x = [ ] ; id ( x ) 4301729448 > > > x = [ ] ; id ( x ) 4301901696 > > > x = [ ] ; id ( x ) 4301729448 | Python reference to an new instance alternating |
Python | fairly new to Python here . Have this code : I originally used raise `` Negative Number ! '' etc but quickly discovered that this was the old way of doing things and you have to call the Exception class . Now it 's working fine but how do I distinguish between my two exceptions ? For the code below it 's printing `` Th... | def someFunction ( num ) : if num < 0 : raise Exception ( `` Negative Number ! '' ) elif num > 1000 : raise Exception ( `` Big Number ! '' ) else : print `` Tests passed '' try : someFunction ( 10000 ) except Exception : print `` This was a negative number but we did n't crash '' except Exception : print `` This was a ... | Python , distinguishing custom exceptions |
Python | Given a list of regions on a line : I want to know which regions a point X belongs to : I know naively ( and my current implementation ) we can just search in O ( n ) , but a more dramatic use case with thousands of regions ( and thousands of look up points , really , is the motivator ) justifies investigating a faster... | regions = [ ( 10,25 ) , ( 18 , 30 ) , ( 45 , 60 ) , ... ] # so on so forth , regions can be overlapping , of variable size , etc . x = 23find_regions ( regions , x ) # == > [ ( 10 , 25 ) , ( 18 , 30 ) ] regions = [ ( start , end ) for ( start , end ) in regions if start < x and x < end ] | Optimized approach to finding which pairs of numbers another number falls between ? |
Python | In Python 2 , are all exceptions that can be raised required to inherit from Exception ? That is , is the following sufficient to catch any possible exception : or do I need something even more general like | try : code ( ) except Exception as e : pass try : code ( ) except : pass | Does ` try ... except Exception as e ` catch every possible exception ? |
Python | I read a cool article on how to avoid creating slow regular expressions . Generally speaking it looks like the longer and more explicit and regex is the faster it will complete . A greedy regex can be exponentially slower . I thought I would test this out by measuring the time it takes to complete a more complex/explic... | import refrom timeit import timeit # This works as expected , the explicit is faster than the greedy. # http_x_real_ip explicit print ( timeit ( setup= '' import re '' , stmt= '' ' r = re.search ( r ' ( \d { 1,3 } \.\d { 1,3 } .\d { 1,3 } .\d { 1,3 } ) ' , '192.168.1.1 999.999.999.999 ' ) ' '' , number=1000000 ) ) 1.15... | Python Regex slower than expected |
Python | I have a string : I want to convert it to : I am trying this : but it returns : ( without the string operation done ) What is the possible reason .title ( ) is not working . ? How to use string operation on the captured group in python ? | str1 = `` abc = def '' str2 = `` abc = # Abc # '' re.sub ( `` ( \w+ ) = ( \w+ ) '' , r '' \1 = % s '' % ( `` # '' +str ( r '' \1 '' ) .title ( ) + '' # '' ) , str1 ) `` abc = # abc # '' | String Operation on captured group in re Python |
Python | If I try the following code , I see that the normal block return value is not returned , but the finally block return value is : A more advanced example is to call a function in each return statement : In that situation , I can see that : In the normal block , the show function is evaluated ( but not return ) , In the ... | > > > def f ( ) : ... try : ... return `` normal '' ... finally : ... return `` finally '' ... > > > f ( ) 'finally ' > > > def show ( x ) : ... print ( x ) ... return x ... > > > def g ( ) : ... try : ... return show ( `` normal '' ) ... finally : ... return show ( `` finally '' ) ... > > > g ( ) normalfinally'finally... | Is it an error to return a value in a finally clause |
Python | Writing doctests for a method that abbreviates a dictionary by searching for a passed key word in the keys of the original dictionary , and returning the new , abbreviated dictionary . My docstring looks as follows : The function works , but when I run py.test 's doctest , the function fails the test as it returns the ... | def abbreviate_dict ( key_word , original_dict ) : `` '' '' > > > orig_dict = { apple_stems : 2 , apple_cores : 5 , apple_seeds : 3 } > > > abbreviate_dict ( 'apple ' , orig_dict ) { 'cores ' : 5 , 'seeds ' : 3 , 'stems ' : 2 } `` '' '' etc . return new_dict Expected : { 'cores ' : 5 , 'seeds ' : 3 , 'stems ' : 2 } Got... | Python : accept unicode strings as regular strings in doctests |
Python | I want to use different API keys for data scraping each time my program is run . For instance , I have the following 2 keys : and the following URL : When the program is run , I would like myUrl to be using apiKey1 . Once it is run again , I would then like it to use apiKey2 and so forth ... i.e : First Run : Second Ru... | apiKey1 = `` 123abc '' apiKey2 = `` 345def '' myUrl = http : //myurl.com/key= ... url = `` http : //myurl.com/key= '' + apiKey1 url = `` http : //myurl.com/key= '' + apiKey2 | Alternating between variables each run |
Python | So I have created a list for multiprocessing stuff ( in particular , it is multiprocessing.Pool ( ) .starmap ( ) ) and want to reduce its memory size . The list is the following : Its memory size calculated from sys.getsizeof ( lst1_1 ) is 317840928Seeing that the type of lst1 is int32 , I thought changing the dtype of... | import sysimport numpy as npfrom itertools import productlst1 = np.arange ( 1000 ) lst3 = np.arange ( 0.05 , 4 , 0.05 ) lst1_1 = list ( product ( enumerate ( lst3 ) , ( item for item in product ( lst1 , lst1 ) if item [ 0 ] < item [ 1 ] ) ) ) lst2 = np.arange ( 1000 , dtype = np.int16 ) lst2_1 = list ( product ( enumer... | Reducing the memory size of a list for multiprocessing.Pool.starmap ( ) |
Python | I 'm making a program that , in part , rolls four dice and subtracts the lowest dice from the outcome . The code I 'm using isThat 's the best I could come up with from my so-far limited coding ability . Is there a better way to make it organize the four dice in order of size , then add together the three highest while... | die1 = random.randrange ( 6 ) + 1die2 = random.randrange ( 6 ) + 1die3 = random.randrange ( 6 ) + 1die4 = random.randrange ( 6 ) + 1if die1 < = die2 and die1 < = die3 and die1 < = die4 : drop = die1elif die2 < = die1 and die2 < = die3 and die2 < = die4 : drop = die2elif die3 < = die1 and die3 < = die2 and die3 < = die4... | Is there a more efficient way to organize random outcomes by size in Python ? |
Python | I want to construct YYYY_WW information from dates ( where WW is a number of week ) . I am struggling with the years ' endings ( beginnings ) , where a part of a week can fall into the neighbouring year:2018_01 is obviously incorrect . Any hint for a simple workaround ? | import datetimeimport pandas as pd # generate range of dates and extract YYYY_WWdates_range = pd.date_range ( start='2018-12-29 ' , end='2019-01-02 ' ) weeks = dates_range.strftime ( `` % Y_ % V '' ) print ( weeks ) # Index ( [ '2018_52 ' , '2018_52 ' , '2018_01 ' , '2019_01 ' , '2019_01 ' ] , dtype='object ' ) | python - Year-week combination for the end or beginning of a year |
Python | I 'm trying to round a pandas DatetimeIndex ( or Timestamp ) to the nearest minute , but I 'm having a problem with Timestamps of 30 seconds - some rounding up , some rounding down ( this seems to alternate ) .Any suggestions to fix this so that 30s always rounds up ? The top result looks fine , with 57m 30s rounding u... | > > > pd.Timestamp ( 2019,6,1,6,57,30 ) .round ( '1T ' ) Timestamp ( '2019-06-01 06:58:00 ' ) > > > pd.Timestamp ( 2019,6,1,6,58,30 ) .round ( '1T ' ) Timestamp ( '2019-06-01 06:58:00 ' ) | Pandas Timestamp rounds 30 seconds inconsistently |
Python | I have an old legacy Fortran code that is going to be called from Python.In this code , data arrays are computed by some algorithm . I have simplified it : let 's say we have 10 elements to proceed ( in the real application its more often 10e+6 than 10 ) : These arrays are then used as follows : What would be a Pythoni... | number_of_elements = 10element_id_1 = [ 0 , 1 , 2 , 1 , 1 , 2 , 3 , 0 , 3 , 0 ] # size = number_of_elementselement_id_2 = [ 0 , 1 , 2 ] # size = max ( element_id_1 ) my_element = one_of_my_10_elements # does not matter where it comes frommy_element_position = elt_position_in_element_id_1 # does not matter howid_1 = ele... | What is a good way of mapping arrays in Python ? |
Python | I am looking for a way in python to make a dictionary of dictionaries based on the desired structure dynamically.I have the data bellow : I give the structure I want them to be like : and finally get the data in this format : This is the manual way that I thought for achieving this : Can you think of a way to be able t... | { 'weather ' : [ 'windy ' , 'calm ' ] , 'season ' : [ 'summer ' , 'winter ' , 'spring ' , 'autumn ' ] , 'lateness ' : [ 'ontime ' , 'delayed ' ] } [ 'weather ' , 'season ' , 'lateness ' ] { 'calm ' : { 'autumn ' : { 'delayed ' : 0 , 'ontime ' : 0 } , 'spring ' : { 'delayed ' : 0 , 'ontime ' : 0 } , 'summer ' : { 'delay... | Get a decision tree in a dictionary |
Python | Dictionaries in python are supposed to have unique keys . Why are you allowed to do this ... Should n't this throw some sort of error ? | d = { ' a ' : ' b ' , ' a ' : ' c ' } | Why does python allow you to create dictionaries with duplicate keys |
Python | I have a tuple of Control values and I want to find the one with a matching name . Right now I use this : Can I do it simpler than this ? Perhaps something like : | listViewfor control in controls : if control.name == `` ListView '' : listView = control listView = controls.FirstOrDefault ( c = > c.name == `` ListView '' ) | Is there a way to find an item in a tuple without using a for loop in Python ? |
Python | ( Sorry , could n't resist the pun ! ) I wonder why it does n't seem possible to translate : into this more readable expression , using dict comprehension : | dict ( [ ( str ( x ) , x ) if x % 2 else ( str ( x ) , x*10 ) for x in range ( 10 ) ] ) { str ( x ) : x if x % 2 else str ( x ) : x*10 for x in range ( 10 ) } | Python dict incomprehension |
Python | currently I am trying to calculate optical flows of moving objects . the objects in particular are the squares that are around the circular knobs : Here is the vanilla image I am trying to process : my concern is about the right bottom-most strip . The two squares are usually unable to be detected when I have tried Can... | import numpy as npimport cv2 as cvfrom matplotlib import pyplot as pltfilename = 'images/Test21_1.tif'image = cv.imread ( filename ) kernel = [ [ 0 , -1 , 0 ] , [ -1 , 5 , -1 ] , [ 0 , -1 , 0 ] ] # sharpen kernel I got from wikipediakernel = np.array ( kernel ) dst = cv.filter2D ( image , -1 , kernel ) ret , thresh = c... | OpenCV : Detect squares in dark background |
Python | I am looking for a way to apply a function n items at the time along an axis . E.g.If I apply sum across the rows 2 items at a time I get : Which is the sum of 1st 2 rows and the last 2 rows.NB : I am dealing with much larger array and I have to apply the function to n items which I can be decided at runtime.The data e... | array ( [ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] , [ 7 , 8 ] ] ) array ( [ [ 4 , 6 ] , [ 12 , 14 ] ] ) array ( [ [ ... [ 1 , 2 , ... ] , [ 3 , 4 , ... ] , [ 5 , 6 , ... ] , [ 7 , 8 , ... ] , ... ] , ... ] ) | Apply function n items at a time along axis |
Python | Is there a function in Python to get the difference between two or more values in a list ? So , in those two lists : I need to calculate the difference between every value in list1 and list2.This gives negative values , but I want the subtraction between the values of the two lists only from highest value to lowest val... | list1 = [ 1 , 5 , 3 , 7 ] list2 = [ 4 , 2 , 6 , 4 ] for i in list1 : for ii in list2 : print i -ii | function of difference between value |
Python | Suppose I have one list which contains anagram strings . For example , And I want to construct a dictionary which contains element of that list as key and anagram strings of that element will be values of that key as a list , Also elements which will be added into list are not repeated as another key of that dictionary... | anList = [ 'aba ' , 'baa ' , 'aab ' , 'cat ' , 'tac ' , 'act ' , 'sos ' , 'oss ' ] anDict = { 'aba ' : [ 'baa ' , 'aab ' ] , 'cat ' : [ 'tac ' , 'act ' ] , 'sos ' : [ 'oss ' ] } | How to add elements in list which is value of dictionary and those elements not be repeated as another keys of that dictionary ? |
Python | How does Python ( 2.6.4 , specifically ) determine list membership in general ? I 've run some tests to see what it does : Which yields : This tells me that Python is probably checking the object references , which makes sense . Is there something more definitive I can look at ? | def main ( ) : obj = fancy_obj ( arg= ' C : \\ ' ) needle = ( 50 , obj ) haystack = [ ( 50 , fancy_obj ( arg= ' C : \\ ' ) ) , ( 1 , obj , ) , needle ] print ( 1 , fancy_obj ( arg= ' C : \\ ' ) , ) in haystack print needle in haystackif __name__ == '__main__ ' : main ( ) FalseTrue | Specifics of List Membership |
Python | I am trying to learn how classes work . I would like to create different classes with some shared elements and others not , but as far as I know I can create it from three different ways : Create a class with all the shared elements and then inherit this class and modify specific methods and attributes in the new class... | class Enemy ( object ) : `` '' '' Enemy ! '' '' '' def __init__ ( self , damage=30 , life=100 , enemy= '' Hero '' ) : # And keep defining the class and its methods and attributes in common with all the enemys class Troll ( Enemy ) : `` '' '' Troll ! '' '' '' def __init__ ( self , defense=0 ) : # And define the specific... | Which strategy follow to create class ? |
Python | I have a sprite which shoots bullets . Sometimes bullets also shoot out of invisible shooters.The switch from opponent to shooter mid-program works but when I want the bullets to shoot in a certain way , with delays between each shot , the bullets seem to become a single line ( the purple thing in the image is the bull... | import pygameimport timeimport itertoolsimport ospygame.init ( ) SCREENWIDTH = 1000SCREENHEIGHT = 650screen = pygame.display.set_mode ( [ SCREENWIDTH , SCREENHEIGHT ] ) screen.fill ( ( 255 , 123 , 67 ) ) pygame.draw.rect ( screen , ( 230 , 179 , 204 ) , ( 0 , 50 , 1000 , 650 ) , 0 ) background = screen.copy ( ) clock =... | `` Bullets '' shot from two Pygame sprites combine into a single long line |
Python | I have two three dimensional arrays , a and b , and want to find the 2D subarray of b with the elements where a had a minimum along the third axis , i.e.Is there a way I can get these values without the double loop ? I am aware of this answer : replace min value to another in numpy arraybut if I want this to work for m... | a=n.random.rand ( 20 ) .reshape ( ( 5,2,2 ) ) b=n.arange ( 20 ) .reshape ( ( 5,2,2 ) ) c=n.argmin ( a,2 ) # indices with minimal value of ad=n.zeros_like ( c ) # the array I wantfor i in range ( 5 ) : for j in range ( 2 ) : d [ i , j ] = b [ i , j , c [ i , j ] ] | Find array corresponding to minimal values along an axis in another array |
Python | How can I stop Python from deleting a name binding , when that name isused for binding the exception that is caught ? When did this change inbehaviour come into Python ? I am writing code to run on both Python 2 and Python 3 : Notice that exc is explicitly bound before the exception handling , so Python knows it is a n... | exc = Nonetry : 1/0 text_template = `` All fine ! `` except ZeroDivisionError as exc : text_template = `` Got exception : { exc.__class__.__name__ } '' print ( text_template.format ( exc=exc ) ) Got exception : ZeroDivisionError Traceback ( most recent call last ) : File `` < stdin > '' , line 8 , in < module > NameErr... | Name binding in ` except ` clause deleted after the clause |
Python | I came accross the following interview question and have no idea how to solve it : Given a pair , e.g cons ( 6,8 ) I am requested to return a and b separetely , e.g in this case 6 , 8 respectively.Meaning , for example , How can this be done ? | def cons ( a , b ) : def pair ( f ) : return f ( a , b ) return pair def first ( pair ) : pass # would return pair 's ` a ` somehowdef second ( pair ) : pass # would return pair 's ` b ` somehow | How to open a closure in python ? |
Python | I am trying to get all < tr class= '' **colour blue** attr1 attr2 '' > from a page . The attrs are different each time , and some of the other sibling < tr > s have colour red , colour pink etc . classes.So I 'm looking for any other characters after colour blue in class to be included in the result . I 've tried using... | soup.find_all ( 'tr ' , { 'class ' : 'colour blue* ' } ) | What 's the equivalent of '* ' for Beautifulsoup - find_all ? |
Python | I have two tables that look like the followingandWhat 's the best way to take the first dataframe , lookup each parameter 's weight in the second dataframe and return a dataframe like the following ? What I was thinking was to write a function given the parameter , and value , subset table2 like the following , table2 ... | ID param1 param2 param30 A12 2 1 11 B15 1 2 12 B20 2 2 1 ... parameter value weight0 param1 1 101 param1 2 132 param2 1 213 param2 2 394 param3 1 495 param3 2 61 ID param1 param2 param30 A12 13 21 491 B15 10 39 492 B20 13 39 49 | Using column header and values from one dataframe to find weights in another dataframe |
Python | I have the following dfHow can I remove lowercase letters from the Name column such that when looking at data [ 'Name ' ] , I have TOM , NICK , KRISH , JACK.I tried the following but no luck , | data = { 'Name ' : [ 'TOMy ' , 'NICKs ' , 'KRISHqws ' , 'JACKdpo ' ] , 'Age ' : [ 20 , 21 , 19 , 18 ] } data [ 'Name ' ] .mask ( data [ 'Name ' ] .str.match ( r'^ [ a-z ] + $ ' ) ) data [ 'Name ' ] = data [ 'Name ' ] .str.translate ( None , string.ascii_lowercase ) | Removing lower case letter in column of Pandas dataframe |
Python | I 'm trying to convert the values of a list using the map function but i am getting a strange result.gives : why does it not return [ ' 4 ' , '58 ' , ' 6 ' ] ? | s = input ( `` input some numbers : `` ) i = map ( int , s.split ( ) ) print ( i ) input some numbers : 4 58 6 < map object at 0x00000000031AE7B8 > | Trouble with map ( ) |
Python | How can I create a Python C extension wheel for MacOS that is backwards compatible ( MacOS 10.9+ ) using MacOS 10.15 ? This is what I have so far : Unfortunately , pip wheel generates a file myapp-0.0.1-cp37-cp37m-macosx_10_15_x86_64.whl , and unlike auditwheel on Linux , delocate-wheel does not modify the name of the ... | export MACOSX_DEPLOYMENT_TARGET=10.9python -m pip wheel . -w wheels -- no-depspython -m pip install delocatefor whl in wheels/*.whl ; do delocate-wheel -w wheels_fixed -v `` $ whl '' done | Create Python C extension using MacOS 10.15 ( Catalina ) that is backwards compatible ( MacOS10.9+ ) |
Python | Why the call to getslice does n't respect the stop I sent in , instead silently substituting 2^63 - 1 ? Does it mean that implementing __getslice__ for your own syntax will generally be unsafe with longs ? I can do whatever I need with __getitem__ anyway , I 'm just wondering why __getslice__ is apparently broken.Edit ... | > > > class Potato ( object ) : ... def __getslice__ ( self , start , stop ) : ... print start , stop ... > > > sys.maxint9223372036854775807 > > > x = sys.maxint + 69 > > > print x9223372036854775876 > > > Potato ( ) [ 123 : x ] 123 9223372036854775807 | Slice endpoints invisibly truncated |
Python | Can you please explain why this happens in Python v3.8 ? Output:2 is within the range of the small integer caching . So why are there different objects with the same value ? | a=round ( 2.3 ) b=round ( 2.4 ) print ( a , b ) print ( type ( a ) , type ( b ) ) print ( a is b ) print ( id ( a ) ) print ( id ( b ) ) 2 2 < class 'int ' > < class 'int ' > False24067014968482406701496656 > > > | Why does n't small integer caching seem to work with int objects from the round ( ) function in Python 3 ? |
Python | I came across this expression , which I thought should evaluate to True but it doesn't.Above statement works as expected but when this : is executed , it evaluates to False.I tried searching for answers but could n't get a concrete one . Can anyone help me understand this behavior ? | > > s = 1 in range ( 2 ) > > s == True > > True 1 in range ( 2 ) == True | Why does `` 1 in range ( 2 ) == True '' evaluate to False ? |
Python | I have a list of lists and I want to be able to refer to the 1st , 2nd , 3rd , etc . column in a list of lists . Here is my code for the list : I want to be able to say something like : I want to know what the python syntax would be for the stuff in parenthesis . | matrix = [ [ 0 , 0 , 0 , 5 , 0 , 0 , 0 , 0 , 6 ] , [ 8 , 0 , 0 , 0 , 4 , 7 , 5 , 0 , 3 ] , [ 0 , 5 , 0 , 0 , 0 , 3 , 0 , 0 , 0 ] , [ 0 , 7 , 0 , 8 , 0 , 0 , 0 , 0 , 9 ] , [ 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 ] , [ 9 , 0 , 0 , 0 , 0 , 4 , 0 , 2 , 0 ] , [ 0 , 0 , 0 , 9 , 0 , 0 , 0 , 1 , 0 ] , [ 7 , 0 , 8 , 3 , 2 , 0 , 0 ,... | How to look at only the 3rd value in all lists in a list |
Python | I found this kind of expression several times in a python program : It seems strange to me , and I think that it has no more sense than : Maybe I do n't know Python enough , and the expression is explained somewhere ? | if variable is not None : dothings ( variable ) if variable : dothings ( variable ) | Does this Python expression make sense ? |
Python | ProblemI have to compute many Fourier transforms . I would like to do these in parallel with my many cores . Note that I do n't want a parallel FFT algorithm , I just want to launch many embarrassingly parallel FFTs.I discover that , while my CPU usage goes up , my time to completion does not decrease.ExampleWe create ... | In [ 1 ] : import numpy as npIn [ 2 ] : x = np.random.random ( 10000000 ) # some random data In [ 3 ] : % time _ = np.fft.rfft ( x ) # cost of one runCPU times : user 589 ms , sys : 23.9 ms , total : 612 msWall time : 613 msIn [ 4 ] : % time _ = np.fft.rfft ( x ) # there is some speedup from mulitple runsCPU times : us... | Increased occupancy without speedup in FFT |
Python | This sounds like an easy question , but I find it surprisingly tricky to get right with good performance.The first algorithm I 've come up with is to draw points randomly , check from a set if it 's already been drawn , and draw it otherwise . This works fine if we are drawing few points but slows down catastrophically... | # ! /usr/bin/env python '' '' '' drawn n random points on the screen `` '' '' import pygamefrom pygame.locals import *import sysimport randomfrom itertools import productn = int ( sys.argv [ 1 ] ) s = pygame.display.set_mode ( ) sx , sy = s.get_size ( ) points = random.sample ( list ( product ( range ( sx ) , range ( s... | How to efficiently draw exactly N points on screen ? |
Python | I very often write code like : where I would like to write : using : Are there functor-creators like idx_f and attr_f in python , and are they of clearer when used than lambda 's ? | sorted ( some_dict.items ( ) , key=lambda x : x [ 1 ] ) sorted ( list_of_dicts , key=lambda x : x [ 'age ' ] ) map ( lambda x : x.name , rows ) sorted ( some_dict.items ( ) , key=idx_f ( 1 ) ) sorted ( list_of_dicts , key=idx_f ( 'name ' ) ) map ( attr_f ( 'name ' ) , rows ) def attr_f ( field ) : return lambda x : get... | Trivial functors |
Python | I understand that the pattern r ' ( [ a-z ] + ) \1+ ' is searching for a repeated multi character pattern in the search string but I do not understand why in case k2 answer is n't 'aaaaa ' ( 5 ' a ' ) : Python 3.6.1 | import rek1 = re.search ( r ' ( [ a-z ] + ) \1+ ' , 'aaaa ' ) k2 = re.search ( r ' ( [ a-z ] + ) \1+ ' , 'aaaaa ' ) k3 = re.search ( r ' ( [ a-z ] + ) \1+ ' , 'aaaaaa ' ) print ( k1 ) # < _sre.SRE_Match object ; span= ( 0 , 4 ) , match='aaaa ' > print ( k2 ) # < _sre.SRE_Match object ; span= ( 0 , 4 ) , match='aaaa ' >... | Regular expressions - different string the same match |
Python | What I did is obviously not something that one would want to do , rather , I was just testing out implementing __hash__ for a given class . I wanted to see if adding a phony 'hashable ' class to a dictionary , then changing it 's hash value would then result in it not being able to access it . My class looks like this ... | class PhonyHash : def __hash__ ( self ) : val = list ( `` A string '' ) return id ( val ) # always different > > > p = PhonyHash ( ) > > > d = { p : `` a value '' } > > > hash ( p ) # changes hash > > > d [ p ] '' a value '' > > > p = PhonyHash ( ) > > > s = { p } > > > p in sFalse | Class with changing __hash__ still works with dictionary access |
Python | I have the following code : Why does this code print the text Hello instead of raise an error ? | with open ( True , ' w ' ) as f : f.write ( 'Hello ' ) | Why does open ( True , ' w ' ) print the text like sys.stdout.write ? |
Python | I have some stats in a trie which is generated periodically . I want to generate flame graphs on the difference between two tries . How do I do that ? | t = pygtrie.StringTrie ( separator=os.path.sep ) for dirpath , unused_dirnames , filenames in os.walk ( ROOT_DIR ) : for filename in filenames : filename = os.path.join ( dirpath , filename ) try : filestat = os.stat ( filename ) except OSError : continue if stat.S_IFMT ( filestat.st_mode ) == stat.S_IFREG : t [ filena... | Construct flame graph from trie |
Python | I could do this in brute force , but I was hoping there was clever coding , or perhaps an existing function , or something I am not realising ... So some examples of numbers I want : The full permutation . Except with results that have ONLY six 1 's . Not more . Not less . 64 or 32 bits would be ideal . 16 bits if that... | 0000000000111111000011111100000000000000010101010101000000001010101010100000000000100100100100100100 | How do I find all 32 bit binary numbers that have exactly six 1 and rest 0 |
Python | I 've inspected .__code__ objects for two functions I deemed different , but found to be identical , for a variety of expressions . If code objects are identical , as far as I understand , they compile to same bytecode , and are thus `` same '' functions.Table below is of things inserted before ; pass that makes g have... | def compare ( fn1 , fn2 ) : for name in dir ( fn1.__code__ ) : if ( name.startswith ( `` co_ '' ) and name not in ( `` co_filename '' , `` co_name '' , `` co_firstlineno '' ) ) : v1 = getattr ( fn1.__code__ , name ) v2 = getattr ( fn2.__code__ , name ) if v1 == v2 : print ( name.ljust ( 18 ) , `` same '' ) else : print... | Why is [ 0 ] a different function but 0 is n't ? |
Python | I 'm trying to implement a basic pipelined model using Graphcore 's PopART framework ( part of the Poplar API ) to speed up my model which is split over multiple processors.I 'm following their example code , but I notice the example does not use the pipelineStage ( ) call , which is used in some of their other applica... | # Dense 1W0 = builder.addInitializedInputTensor ( init_weights ( num_features , 512 ) ) b0 = builder.addInitializedInputTensor ( init_biases ( 512 ) ) with builder.virtualGraph ( 0 ) : x1 = builder.aiOnnx.gemm ( [ x0 , W0 , b0 ] , debugPrefix= '' gemm_x1 '' ) x2 = builder.aiOnnx.relu ( [ x1 ] , debugPrefix= '' relu_x2 ... | Difference between virtualGraph and pipelineStage Graphcore 's PopART/Poplar libraries |
Python | I have a list of coordinates : I have a string as follows : I want to replace intervals indicated in pairs in coordinates as start and end with character ' N'.The only way I can think of is the following : The desired output would be : where intervals , [ 1,5 ) , [ 10,15 ) and [ 25 , 35 ) are replaced with N in line.Th... | coordinates = [ [ 1,5 ] , [ 10,15 ] , [ 25 , 35 ] ] line = 'ATCACGTGTGTGTACACGTACGTGTGNGTNGTTGAGTGKWSGTGAAAAAKCT ' for element in coordinates : length = element [ 1 ] - element [ 0 ] line = line.replace ( line [ element [ 0 ] : element [ 1 ] ] , ' N'*length ) line = 'ANNNNGTGTGNNNNNACGTACGTGTNNNNNNNNNNGTGKWSGTGAAAAAKCT... | Replace a list of characters with indices in a string in python |
Python | I may break the code up for readability reasons . So ... into something likeHowever , the extra awaits mean that these are not strictly equivalentAnother concurrent task can run code between print ( 'top ' ) and print ( ' 1 ' ) , so makes race conditions a touch more likely for certain algorithms.There is ( presumably ... | async coro_top ( ) : print ( 'top ' ) print ( ' 1 ' ) # ... More asyncio code print ( ' 2 ' ) # ... More asyncio code async coro_top ( ) : print ( 'top ' ) await coro_1 ( ) await coro_2 ( ) async coro_1 ( ) print ( ' 1 ' ) # ... More asyncio codeasync coro_2 ( ) print ( ' 2 ' ) # ... More asyncio code | Call a coroutine without yielding the event loop |
Python | Suppose I have the dict of a module ( via vars ( mod ) , or mod.__dict__ , or globals ( ) ) , e.g . : Given the dict d , how can I get back the module mod ? I.e . I want to write a function get_mod_from_dict ( d ) , which returns the module if the dict belongs to a module , or None : If get_mod_from_dict returns a modu... | import modd = vars ( mod ) > > > get_mod_from_dict ( d ) < module 'mod ' > mod = get_mod_from_dict ( d ) assert mod is None or mod.__dict__ is d def get_mod_from_dict ( d ) : mods = { id ( mod.__dict__ ) : mod for ( modname , mod ) in sys.modules.items ( ) if mod and modname ! = `` __main__ '' } return mods.get ( id ( ... | Get module instance given its vars dict |
Python | How can I make sure that the variables brk1_int_c , brk1_ext_c , brk2_int_c , brk2_ext_c within the parseTwoPoleBreakres get placed into the inputList instead of the brk1_int_c , brk1_ext_c , brk2_int_c , brk2_ext_c being called outside of the function ? I 'm having difficulty with my parseTwoPoleBreakers function . I ... | brk1_int_c=str ( df1 [ 'Unnamed : 1 ' ] [ aRowNum ] ) # starts at row 7,13,19,25,31,37,43,49. addition of 6brk1_ext_c=str ( df1 [ 'Unnamed : 2 ' ] [ aRowNum ] ) brk2_int_c=str ( df1 [ 'Unnamed : 1 ' ] [ bRowNum ] ) brk2_ext_c=str ( df1 [ 'Unnamed : 2 ' ] [ bRowNum ] ) ` NULL , NULL , NULL , NULL , NULL , NULL , NULL , ... | Calling Parent Variables into List |
Python | Executing the script with the space after `` conv : '' the results is a `` newline '' as below : how remove \n ( new line ) ? removing the space character after conv : the script runs perfectly.results is : I 'd like have : | lines = lines.replace ( `` www . `` , '' conv : `` ) conv : yahoo.comconv : yahoo.itconv : yahoo.orgconv : yahoo.net # ! /usr/bin/pythonwith open ( '/home/user/tmp/prefix.txt ' ) as f : lines = f.read ( ) lines = lines.replace ( `` http : // '' , '' '' ) lines = lines.replace ( `` www . `` , '' conv : '' ) urls = [ url... | remove \n after `` lines.replace '' |
Python | I have a simple little decorator , that caches results from function calls in a dict as a function attribute.I now want to add the possibility to empty the cache . So I change the dynamic_programming ( ) function like this : Now let 's assume I use this little thing to implement a Fibonacci number function : But now wh... | from decorator import decoratordef _dynamic_programming ( f , *args , **kwargs ) : try : f.cache [ args ] except KeyError : f.cache [ args ] = f ( *args , **kwargs ) return f.cache [ args ] def dynamic_programming ( f ) : f.cache = { } return decorator ( _dynamic_programming , f ) def dynamic_programming ( f ) : f.cach... | Reassign a function attribute makes it 'unreachable ' |
Python | I have a 3D dimensional array.I would like to calculate the percentile rank of a particular value along axis = 0.E.g . if the value = 4 , the output is expected to be : where the 0.25 at [ 0 ] [ 0 ] is the percentile rank of 4 in [ 0 , 6 , 12 , 18 ] , etc.If the value = 2.5 , the output is expected to be : I was thinki... | > > > M2 = np.arange ( 24 ) .reshape ( ( 4 , 3 , 2 ) ) > > > print ( M2 ) array ( [ [ [ 0 , 1 ] , [ 2 , 3 ] , [ 4 , 5 ] ] , [ [ 6 , 7 ] , [ 8 , 9 ] , [ 10 , 11 ] ] , [ [ 12 , 13 ] , [ 14 , 15 ] , [ 16 , 17 ] ] , [ [ 18 , 19 ] , [ 20 , 21 ] , [ 22 , 23 ] ] ] ) [ [ 0.25 , 0.25 ] , [ 0.25 , 0.25 ] , [ 0.25 , 0.0 ] ] [ [ 0... | Calculate the percentile rank of a value in a multi-dimensional array along an axis |
Python | I am planning to implement C++-like constructor/destructor functionality to one of my Python classes using the handy with statement . I 've come accross this statement only for file IO up to now , but I thought it would be rather helpful for connection-based communication tasks as well , say sockets or database connect... | class MyConnection : def __init__ ( self ) : pass def __enter__ ( self ) : print `` constructor '' # TODO : open connections and stuff # make the connection available in the with-block return self def __exit__ ( self , *args ) : print `` destructor '' # TODO : close connections and stuffwith MyConnection ( ) as c : # T... | What things to be aware of when using the with-statement for own classes ? |
Python | I have 3 objects that I am populating into a JSON file format . The objects come from an API which needs rolled out to access as such : Produces output like this : My desired output : As you can see , I need each nested dictionary enclosed in a list at each level and I need to add a key/value pair at each level ( excep... | my_dict = { } for elem_a in list_a : for elem_b in elem_a : for elem_c in elem_b : elem_c_info = { `` name '' : elem_c.prop1 , `` ID '' : elem_c.prop2 , `` GPA '' : elem_c.prop3 } my_dict.setdefault ( `` university '' , { } ) \ .setdefault ( str ( elem_a ) , { } ) \ .setdefault ( str ( elem_b ) , { } ) \ .setdefault ( ... | Nested lists of dictionaries |
Python | I have a .txt file with the following contents : I want to overwrite the file such that these are its new contents : Basically I want to turn the .txt file into a python dictionary so I can manipulate it . Are there built in libraries for this sort of task ? Here is my attempt : I 'm succeeding in getting the quotes ; ... | norway swedenbhargama bhargamaforbisganj forbesganjcanada usaankara turkey 'norway ' : 'sweden ' , 'bhargama ' : 'bhargama ' , 'forbisganj ' : 'forbesganj ' , 'canada ' : 'usa ' , 'ankara ' : 'turkey ' import retarget = open ( 'file.txt ' , ' w ' ) for line in target : target.write ( re.sub ( r ' ( [ a-z ] + ) ' , r ''... | Python : regex to make a python dictionary out of a sequence of words ? |
Python | Working in Python3 . Say you have a million beetles , and your task is to catalogue the size of their spots . So you will make a table , where each row is a beetle and the number in the row represent the size of spots ; Also , you decide to store this in a numpy array , for which you pad the lists with None ( numpy wil... | [ [ .3 , 1.2 , 0.5 ] , [ .6 , .7 ] , [ 1.4 , .9 , .5 , .7 ] , [ .2 , .3 , .1 , .7 , .1 ] ] [ [ .3 , 1.2 , 0.5 , None , None ] , [ .6 , .7 , None , None , None ] , [ 1.4 , .9 , .5 , .7 , None ] , [ .2 , .3 , .1 , .7 , .1 ] ] | Reasonable way to have different versions of None ? |
Python | I want to merge two arrays in python in a special way . The entries with an odd index of my output array out shall be the coresponding entries of my first input array in0 . The entries with an even index in out shall be the coresponding entries of my second input array in1.in0 , in1 and out are all the same length.Exam... | in0 = [ 0 , 1 , 2 , 3 ] in1 = [ 4 , 5 , 6 , 7 ] out = [ 0 , 5 , 2 , 7 ] | Combine elements from two lists |
Python | I have a column with a series of timestamps in it . Originally I thought they are in Unix timestamps system so I used the following code to convert them to date time.however , it gave me odd results so I researched a bit more and found out the timestamps are basically using the .net epoch , which is midnight 01/01/0001... | big_frame [ 'date ' ] = pd.to_datetime ( big_frame [ 'filename ' ] , unit='s ' ) 63730342900 14/07/2020 17:01:40 0 637290451451 637290451452 637290451463 637290451464 637290451465 637290451476 637290451477 63729045147 | Convert epoch , which is midnight 01/01/0001 , to DateTime in pandas |
Python | This is my sample DataFrame . I want to apply groupby on column ' A ' , Apply rolling sum on column ' B ' based on the value of column ' C ' , means when A is 1 so window size should be 2 and instead of NaN I want the sum of remaining values regardless of window size . Currently my output is : code for above : df [ ' B... | A B C0 1 10 21 1 15 22 1 14 23 2 11 44 2 12 45 2 13 46 2 16 47 1 18 2 A 1 0 25.0 1 29.0 2 32.0 7 NaN2 3 23.0 4 25.0 5 29.0 6 NaN A B C Rolling_sum0 1 10 2 251 1 15 2 292 1 14 2 327 1 18 2 183 2 11 4 524 2 12 4 415 2 13 4 296 2 16 4 16 | How to pass dataframe column value as window size after df.groupby ? |
Python | If I have a dict for exampleHowever , I do n't know how many nested items are in this dict . Instead I have a list of keys like : What is an elegant way to set d [ ' a ' ] [ ' y ' ] [ ' z ' ] [ ' 1 ' ] = 'winner ' ? Here 's what I 've tried : | d = { ' a ' : { `` x '' : [ ] , `` y '' : { `` z '' : { `` 1 '' : 'loser ' } } } } print ( d [ ' a ' ] [ ' y ' ] [ ' z ' ] [ ' 1 ' ] ) # = > loser [ ' a ' , ' y ' , ' z ' , ' 1 ' ] l = [ ' a ' , ' y ' , ' z ' , ' 1 ' ] def change_the_value ( d , l , value ) : if len ( l ) == 1 : d [ l [ 0 ] ] = value if len ( l ) == 2 ... | How to set `` nth '' element of a nested python dict with given list location ? |
Python | I am using a Homebrew-installed Python on my Mac ( running OS X 10.13.1 ) , and of late , I ’ ve noticed that the interpreter takes a frustratingly long time to start up.In setting out to try to solve this problem , I did a simple check with time : … which revealed the egregiousness of the issue : 12 seconds ! I then u... | PIPER-ALPHA : ~ $ time bpython -c 'pass'real 0m12.141suser 0m1.662ssys 0m10.073s PIPER-ALPHA : ~ $ PYTHONVERBOSE=1 bpython -c 'pass ' 2 > & 1 | tee -a /tmp/bpython-startup-messages | gnomon | Python interpreter takes ~12 seconds to start up , all of which is spent in ` import pyexpat ` |
Python | I have a df , where the data looks like this : I want to fill in the blank cells in the Time variable according to the calendar year . So : I saw a post where pandas could be used to fill in numeric values , but since my variable is n't necessarily defined in a numeric way , I 'm not entirely sure how to apply it in th... | Time Value 60.8 Jul 2019 58.1 58.8 56.9 Oct 2019 51.8 54.6 56.8 Jan 2020 58.8 54.2 51.3 Apr 2020 52.2 Time Value Jun 2019 60.8 Jul 2019 58.1 Aug 2019 58.8 Sep 2019 56.9 Oct 2019 51.8 Nov 2019 54.6 Dec 2019 56.8 Jan 2020 58.8 Feb 2020 54.2 Mar 2020 51.3 Apr 2020 52.2 totalmonth= [ `` , 'Jul 2019 ' , `` , `` , 'Oct 2019 ... | How to fill in blank cells in df based on string in sequential row , Pandas |
Python | Hi I have about 16 20+ gb files on a server that I need to read specific entries from , I have the code working that reads the file in the correct order if I have one of the files saved on my computer Now I need to read the files from the server without downloading each file . I was looking into paramiko and was able t... | f = open ( 'biodayk1.H2009 ' , 'rb ' ) lbl = array.array ( ' f ' ) bio = 0 for day in range ( iday ) : f.seek ( nx*ny*km*bio*4 , 1 ) lbl.read ( f , nx*ny*km ) # reads the desired ibio f.seek ( nx*ny*km* ( 10 - bio ) *4 , 1 ) # skips the next ibios f.close ( ) | iterating through a large 20+ gb file from a server with python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.