lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | What is the best way for me to create a dictionary from a string that key is each character and its upper case and value is its opposite case ? I can use two line dictionary comprehensive but any better way ? ex : string : abc = > { ' a ' : ' A ' , ' b ' : ' B ' , ' c ' : ' C ' , ' C ' : ' c ' , ' B ' : ' b ' , ' A ' :... | string = 'abc 'd = { i : i.upper ( ) for i in string } d.update ( { i.upper ( ) : i for i in string } ) | create a dictionary from string that each character is key and value |
Python | I was trying to print the result of a loop in the same line using python 3 and after reading Python : for loop - print on the same line I managed to do it.The problem now is when I insert before the print.I would like to print the first character , wait two seconds , then the second , wait two more seconds , etc.Here t... | for x in range ( 1,10 ) : print ( x , end= '' '' ) time.sleep ( 2 ) for x in range ( 1,10 ) : time.sleep ( 2 ) print ( x , end= '' '' ) | Interpolate sleep ( ) and print ( ) in the same line inside a for loop using python 3 |
Python | Firstly , there is class A with two class variables and two instance variables : We can see that both class variable and instance variable of int type works fine : However , things have changed if we check the function type variables : I known that python has translated a.cfun ( 1,2 ) to A.cfun ( a,1,2 ) and then error... | In [ 1 ] : def fun ( x , y ) : return x + yIn [ 2 ] : class A : ... : cvar = 1 ... : cfun = fun ... : def __init__ ( self ) : ... : self.ivar = 100 ... : self.ifun = fun In [ 3 ] : a = A ( ) In [ 4 ] : a.ivar , a.cvarOut [ 4 ] : ( 100 , 1 ) In [ 5 ] : a.ifun , a.cfunOut [ 5 ] : ( < function __main__.fun > , < bound met... | What 's the difference between class variables of different types ? |
Python | I have a range of values ( L , R , U , D ) and two variables , d and newd , containing one of them . I need to check if d and newd are in the same subset ( L , R or U , D ) or not.I know I can do this : this indeed returns False if they both have values in L , R or U , D , and True otherwise . Still , I find it much re... | d in { ' L ' , ' R ' } and newd in { ' U ' , 'D ' } or d in { ' U ' , 'D ' } and newd in { ' L ' , ' R ' } | Check if two variables have values from two different sets , the DRY way |
Python | I recently received a bundle of Python code , written by a graduate student at an academic lab , and consisting of a Python script and about half dozen single-file Python modules , used by by the script . All these files ( script and modules ) are on the same directory.I wanted to use pip to install this code in a virt... | Name : whatever | How does the value of the name parameter to setuptools.setup affect the results ? |
Python | I want to slice by range in Python and it seems like it 's not possible.Why do I want to do this ? I want to define `` what to slice '' in one part of my script , put that in a variable , and do the actual slicing elsewhere . Like this : Is it possible , and if not , how to do something similar correctly and `` right '... | > > > a='0123456789 ' > > > a [ range ( 1,2 ) ] Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > TypeError : string indices must be integers , not list myrange=range ( 1,2 ) a='0123456789 ' a [ myrange ] # < -- -- -raises TypeError | Slicing by range |
Python | I 'm trying to find a good interval of colors for color masking in order to extract skin from images.I have a database with images and masks to extract skin from those images . here 's an example of a sample : I 'm applying the mask for each image in order to get something like this : I 'm getting all the pixels from a... | for i , ( img_color , img_mask ) in enumerate ( zip ( COLORED_IMAGES , MASKS ) ) : # masking img_masked = cv2.bitwise_and ( img_color , img_mask ) # transforming into pixels array img_masked_pixels = img_masked.reshape ( len ( img_masked ) * len ( img_masked [ 0 ] ) , len ( img_masked [ 0 ] [ 0 ] ) ) # merging all pixe... | How to use an optimization algorithm to find the best possible parameter |
Python | Here is an example class : As you can see , I 'm using exec to optimize the creation of multiple property ( ) objects . I often read that using exec is bad and that it is a security hole in your program . In this case , is it ? | from datetime import datetimeclass Article : published = datetime.now ( ) for propname in `` year month day hour minute second '' .split ( ) : exec `` % s = property ( lambda self : self.published. % s ) '' % ( propname , propname ) del propname | Is using 'exec ' under controlled conditions a security threat ? |
Python | I tried to google something about it . Why do non-data descriptors work with old-style classes ? Docs say that they should not : '' Note that descriptors are only invoked for new style objects or classes ( ones that subclass object ( ) or type ( ) ) . `` .Thanks . | class Descriptor ( object ) : def __init__ ( self ) : self.x = 1 def __get__ ( self , obj , cls=None ) : return self.xclass A : x = Descriptor ( ) a = A ( ) a.x > > > 1 | Python descriptors with old-style classes |
Python | I would like to add a semi-transparent rectangle filled with a solid colour to an already loaded semi-transparent PNG . Here 's an example input image I am using : That image is loaded with a standard cv2.IMREAD_UNCHANGED flag so that alpha channel is perfectly preserved . That input image is stored in the image variab... | # get image dimensionsimgHeight , imgWidth = image.shape [ :2 ] # create empty overlay layer with 4 channelsoverlay = np.zeros ( ( imgHeight , imgWidth , 4 ) , dtype = `` uint8 '' ) # draw semi-transparent red rectangleoverlay [ 200:300 , 0 : imgWidth ] = ( 0 , 0 , 255 , 200 ) # extract alpha channel from overlayalpha ... | Alpha blending two images with OpenCV and/or Numpy |
Python | I am trying to make a simple drawing application using Python and gnomecanvas . Sadly , there appears to be no documentation for the Python bindings for gnomecanvas whatsoever . Thus , I am bumbling around using code samples and trying to guess from the C bindings.As it is , I have the code working by keeping a list of... | def get_pointer_coords ( self , event ) : return self.window_to_world ( event.x , event.y ) def render_path ( self ) : path_def = gnomecanvas.path_def_new ( self.cur_path ) self.current_item.set_bpath ( path_def ) def button_press ( self , event ) : is_core = event.device is gdk.device_get_core_pointer ( ) if is_core :... | Is there a way to append to an existing gnome canvas bpath in Python ? |
Python | From Python : When I check through Bash : Why does this return a different result ? | > > > import os > > > s = os.stat ( '/etc/termcap ' ) > > > print ( oct ( s.st_mode ) ) **0o100444** $ stat -f `` % p % N '' /etc/termcap**120755** /etc/termcap | Why do file permissions show different in Python and bash ? |
Python | I 'm trying to make a code to rewrite a specific line from a .txt file.I can get to write in the line i want , but i ca n't erase the previous text on the line.Here is my code : ( i 'm trying a couple of things ) You can use this code to make a test file for testing : Edit : For Some reason , if i use 'if count==5 : ' ... | def writeline ( file , n_line , text ) : f=open ( file , ' r+ ' ) count=0 for line in f : count=count+1 if count==n_line : f.write ( line.replace ( str ( line ) , text ) ) # f.write ( '\r'+text ) with open ( 'writetest.txt ' , ' w ' ) as f : f.write ( ' 1 \n2 \n3 \n4 \n5 ' ) writeline ( 'writetest.txt',4 , 'This is the... | How to erase line from text file in Python ? |
Python | What is & = in python ? For example : I found it in the twilio python library : https : //github.com/twilio/twilio-python/blob/master/twilio/util.py # L62Why do n't they just compare the strings directly return string1 == string2 and compare each character ? | for c1 , c2 in izip ( string1 , string2 ) : result & = c1 == c2 | What is the `` & = '' operator and why does Twilio use it when comparing strings ? |
Python | Here 's a bit of a program I 'm writing that will create a csv categorizing a directory of files : Basically , the user picks a folder and the program denotes problem files , which can be of several types ( just two listed here : no files with uppercase letters , no php or python files ) . There will be probably five o... | matches = [ ] for root , dirnames , filenames in os.walk ( directory ) : for filename in fnmatch.filter ( filenames , '* [ A-Z ] * ' ) : matches.append ( [ os.path.join ( root , filename ) , `` No Capital Letters ! '' ] ) test = re.compile ( `` .*\ . ( py|php ) '' , re.IGNORECASE ) for filename in filter ( test.search ... | Pythonic way to process multiple for loops with different filters against the same list ? |
Python | A easier way has updated in the end of the question . What I haveI have a user-user correlation matrix called matrixcorr_of_user like the one below : What I want For every user , I just want to keep the 2 other users that are the most similar to him ( the highest correlation values per row after excluding the elements ... | userId 316 320 359 370 910userId 316 1.000000 0.202133 0.208618 0.176050 0.174035320 0.202133 1.000000 0.242837 0.019035 0.031737359 0.208618 0.242837 1.000000 0.357620 0.175914370 0.176050 0.019035 0.357620 1.000000 0.317371910 0.174035 0.031737 0.175914 0.317371 1.000000 Out [ 40 ] : userId 316 320 359 370 910corr_us... | Is there a elegant way to only keep top [ 2~3 ] value for each row in a matrix ? |
Python | I am working on a custom file path class , which should always execute a functionafter the corresponding system file has been written to and its file objectclosed . The function will upload the contents of file path to a remote location.I want the upload functionality to happen entirely behind the scenes from a userper... | import osclass CustomPath ( os.PathLike ) : def __init__ ( self , remote_path : str ) : self._local_path = `` /some/local/path '' self._remote_path = remote_path def __fspath__ ( self ) - > str : return self._local_path def upload ( self ) : # Upload local path to remote path . custom_path = CustomPath ( `` some remote... | Python Callback for File Object Close |
Python | I have an array A : The length of consecutive '1s ' would be : with the corresponding starting indices : The original arrays are huge and I prefer a solution with less for-loop.Edit ( Run time ) : Quang 's solution : Jacco 's solution : Dan 's solution ( works with special cases as well ) : Run time analysis with 10000... | import numpy as npA = np.array ( [ 0 , 0 , 1 , 1 , 1 , 0 , 1 , 1 , 0 ,0 , 1 , 0 ] ) output : [ 3 , 2 , 1 ] idx = [ 2 , 6 , 10 ] import numpy as npimport timeA = np.array ( [ 0 , 0 , 1 , 1 , 1 , 0 , 1 , 1 , 0 ,0 , 1 , 0 ] ) def LoopVersion ( A ) : l_A = len ( A ) size = [ ] idx = [ ] temp_idx = [ ] temp_size = [ ] for i... | Fast way to find length and start index of repeated elements in array |
Python | I have a form with a dependent drop-down . This secondary drop-down is hidden whenever the primary option selected does not have any secondary options , and when the page first loads . Whenever the form is submitted , only the first field gets cleared out , since most of the time the drop-downs remain the same , howeve... | class WarehouseForm ( AppsModelForm ) : class Meta : model = EmployeeWorkAreaLog widgets = { 'employee_number ' : ForeignKeyRawIdWidget ( EmployeeWorkAreaLog._meta.get_field ( 'employee_number ' ) .remote_field , site , attrs= { 'id ' : 'employee_number_field ' } ) , } fields = ( 'employee_number ' , 'work_area ' , 'st... | How to `` load '' dependent drop down upon page load ? |
Python | My question is about the rule that pandas uses to compare a column with type `` object '' with an integer . Here is my code : Why does the `` c2 '' column get True for all ? P.S . I also tried : | In [ 334 ] : dfOut [ 334 ] : c1 c2 c3 c4id1 1 li -0.367860 5id2 2 zhao -0.596926 5id3 3 sun 0.493806 5id4 4 wang -0.311407 5id5 5 wang 0.253646 5In [ 335 ] : df < 2Out [ 335 ] : c1 c2 c3 c4id1 True True True Falseid2 False True True Falseid3 False True True Falseid4 False True True Falseid5 False True True FalseIn [ 33... | How does the Pandas deal with the situation when a column with type `` object '' is compared with an integer ? |
Python | I have a script , which parses a few arguments , and has some expensive imports , but those imports are only needed if the user gives valid input arguments , otherwise the program exits . Also , when the user says python script.py -- help , there is no need for those expensive imports to be executed at all.I can think ... | import argparsedef parse_args ( ) : parser = argparse.ArgumentParser ( ) parser.add_argument ( ' -- argument ' , type=str ) args = parser.parse_args ( ) return argsif __name__ == `` __main__ '' : args = parse_args ( ) import gensim # expensive importimport blahblahblahdef the_rest_of_the_code ( args ) : passif __name__... | how to elegantly parse argumens in python before expensive imports ? |
Python | I would like to generate a random potential in 1D or 2D spaces with a specified autocorrelation function , and according to some mathematical derivations including the Wiener-Khinchin theorem and properties of the Fourier transforms , it turns out that this can be done using the following equation : where phi ( k ) is ... | import numpy as npfrom numpy.fft import fft , ifftimport matplotlib.pyplot as plt # # The Gaussian autocorrelation function def c ( x , V0 , rho ) : return V0**2 * np.exp ( -x**2/rho**2 ) x_min , x_max , interval_x = -10 , 10 , 10000x = np.linspace ( x_min , x_max , interval_x , endpoint=False ) V0 = 1 # # the correlat... | Generating correlated random potential using fast Fourier transform |
Python | I 'm trying to develop a Python script to examine every sentence in Barack Obama 's second inaugural address and find similar sentences in past inaugurals . I 've developed a very crude fuzzy match , and I 'm hoping to improve it.I start by reducing all inaugurals to lists of stopword-free sentences . I then build a fr... | # compare two lemmatized sentences . Assumes stop words already removed . frequencies is dict of frequencies across all inaugural def compare ( sentA , sentB , frequencies ) : intersect = [ x for x in sentA if x in sentB ] N = [ frequencies [ x ] for x in intersect ] # calculate sum that weights uncommon words based on... | detect allusions ( e.g . very fuzzy matches ) in language of inaugural addresses |
Python | I 'm using the python module subprocess to call a program and redirect the possible std error to a specific file with the following command : I want that the `` std.err '' file is created only if there are errors , but using the command above if there are no errors the code will create an empty file.How i can make pyth... | with open ( `` std.err '' , '' w '' ) as err : subprocess.call ( [ `` exec '' ] , stderr=err ) | Subprocess error file |
Python | I have a dataframe df1 that contains rows of tokenized strings : I also have a dataframe df2 that contains single-word strings as well as a score pertaining to each word : What is the best way to use df2 as a sort of lookup `` table '' that I can also use to help perform calculations ? For each row in df1 , I need to c... | df1 = pd.DataFrame ( data = { 'tokens ' : [ [ 'auditioned ' , 'lead ' , 'role ' , 'play ' , 'play ' ] , [ 'kittens ' , 'adopted ' , 'family ' ] , [ 'peanut ' , 'butter ' , 'jelly ' , 'sandwiches ' , 'favorite ' ] , [ 'committee ' , 'decorated ' , 'gym ' ] , [ 'surprise ' , 'party ' , 'best ' , 'friends ' ] ] } ) df2 = ... | How to check a dataframe consisting of a list of strings against a lookup dataframe and perform calculations ? |
Python | type ( 3 , ) returns the int type , while returns the tuple type.Why ? | t = 3 , type ( t ) | Type ( 3 , ) returns an integer instead of a tuple in python , why ? |
Python | A callable object is supposed to be so by defining __call__ . A class is supposed to be an object… or at least with some exceptions . This exception is what I 'm failing to formally clarify , thus this question posted here.Let A be a simple class : The first function is purposely named “ call ” , to make clear the purp... | class A ( object ) : def call ( *args ) : return `` In ` call ` `` def __call__ ( *args ) : return `` In ` __call__ ` `` a = A ( ) # Think of it as ` a = magic ` and forget about ` A ( ) ` print ( A.call ( ) ) print ( a.call ( ) ) print ( A ( ) ) print ( a ( ) ) > > > In ` call ` > > > In ` call ` > > > < __main__.A ob... | How do Python tell “ this is called as a function ” ? |
Python | When I do the following in IPython notebookI seeWhat 's going on here ? How do I print a list of Unicode strings ? ( ie I want to see [ ' ½ ' ] ) EditSo from comments , looks like the difference is that `` print s '' uses s.__str__ and `` s '' , `` print [ s ] '' uses it 's s.__repr__ | s= ' ½'sprint sprint [ s ] '\xc2\xbd ' ½ [ '\xc2\xbd ' ] | Different encodings used in in `` print s '' vs `` print [ s ] '' ? |
Python | Today I noticed something odd in my code , and discovered that in certain situations it run down to the execution of the following : which results in my_list being the following : At the beginning I was quite confused , than I understood that the interpreter is first converting the list to a numpy array , and then tryi... | my_list = [ 0 ] + np.array ( [ ] ) array ( [ ] , dtype=float64 ) > > > np.array ( [ 0 ] ) + np.array ( [ ] ) array ( [ ] , dtype=float64 ) | python list + empty numpy array = empty numpy array ? |
Python | I am trying to overcome the flaws of sub-classing Python 's float by using a different class hierarchy of numbers . However the following code : yields the error : AttributeError : 'module ' object has no attribute 'numbers'How can I overcome this ? | from sympy import *import sympy.core.numbersf = 1.123456789n = N ( f , 8 ) print nprint type ( n ) sympy.core.numbers.Float.__str__ = lambda f : `` { : .8f } '' .format ( f ) print n | How can I override the __str__ method of sympy.core.numbers.Float ? |
Python | So I have a dataframe that contains some wrong information that I want to fix : id refers to a business , and this DataFrame is a small example slice of a much larger one that shows how a business moves . Each record is a unique location , and I want to capture the first and last year it was there . The current 'LastYe... | import pandas as pdtuples_index = [ ( 1,1990 ) , ( 2,1999 ) , ( 2,2002 ) , ( 3,1992 ) , ( 3,1994 ) , ( 3,1996 ) ] index = pd.MultiIndex.from_tuples ( tuples_index , names= [ 'id ' , 'FirstYear ' ] ) df = pd.DataFrame ( [ 2007 , 2006 , 2006 , 2000 , 2000 , 2000 ] , index=index , columns= [ 'LastYear ' ] ) dfOut [ 4 ] : ... | Python Pandas Groupby Resetting Values Based on Index |
Python | I am making a game in which the player has to use a bowl to catch falling items . I have some images of items in a list and an image of a bowl that is used to catch the items . The items keep on falling and reset to the top of the screen if they reach the boundary ( bottom edge ) . I got this logic done which allows th... | import mathimport pygameimport randompygame.init ( ) display_width = 800display_height = 600game_display = pygame.display.set_mode ( ( display_width , display_height ) ) clock = pygame.time.Clock ( ) pygame.display.set_caption ( `` Catch the Ball '' ) white = ( 255 , 255 , 255 ) black = ( 0 , 0 , 0 ) red = ( 255 , 0 , ... | How to detect collisions between two rectangular objects or images in pygame |
Python | If I create hdf5 file with pandas with following code : all series are empty , so why `` store.h5 '' file takes 1.1GB space on hardrive ? | import pandas as pdstore = pd.HDFStore ( `` store.h5 '' ) for x in range ( 1000 ) : store [ `` name '' +str ( x ) ] = pd.Series ( ) | Why if I put multiple empty Pandas series into hdf5 the size of hdf5 is so huge ? |
Python | The following does not raise : although this does : Is this a known problem ? What can I do to fix it ? I need to inherit from something that looks exactly like a list and create an abstract inheritor . Thank you . | from abc import ABCMeta , abstractmethodclass Test ( list , metaclass=ABCMeta ) : @ abstractmethod def test ( self ) : passtest = Test ( ) from abc import ABCMeta , abstractmethodclass Test ( metaclass=ABCMeta ) : @ abstractmethod def test ( self ) : passtest = Test ( ) | Python 3.7 : Inheriting list , abstract ignored |
Python | Is it possible to patch together a copy-and-pastable invocation for a python program from the invoked program itself ? It does n't have to be exactly the same invocation string , but the arguments should parse to the same thing.Note that ' '.join ( sys.argv ) wo n't cut it , unfortunately . The main problem I have with... | [ 'dummy.py ' , ' 1 2 ' ] dummy.py 1 2 import sysprint ( sys.argv ) print ( ' '.join ( ' '' { } '' '.format ( s ) for s in sys.argv ) ) python dummy2.py ' `` breaking `` ' | Re-creating a python invocation |
Python | I have a growing number of scripts that make up a program I am writing and decided it was time to clean up my source tree and package them up correctly . I 'm sure this is a simple question but I ca n't find out how to do it.If I have a group of modules , that fit together , but one should be a top-level module and the... | myprogram/ mystuff.py mystuff/ __init__.py tests/ __init__.py test1.py test2.py ... | Packages `` within '' modules |
Python | Below is a list of hostnames that is stored in a text file.for the sake of displaying it shortly it needs to be parsed and rewritten/displayed as can you guys help me on this , any suggestions will be helpful . | web1.maxi.comweb3.maxi.comweb4.maxi.comweb5.maxi.comweb6.maxi.comweb7.maxi.comweb8.maxi.comweb9.maxi.comweb11.maxi.com web [ 1,3-9,11 ] .maxi.com | parse and rearrange hostnames |
Python | I have a very big list of words ( around 200k ) : I created this regex , with fuzziness : I have input sentences : What I want to get is this : I tried this for example : But this outputs me : Any idea how to get the right answer with corrected words ? What I want is to get the regex capturing group for each match but ... | [ `` cat '' , `` the dog '' , `` elephant '' , `` the angry tiger '' ] regex = `` ( cat ) { e < 3 } | ( the dog ) { e < 3 } | ( elephant ) { e < 3 } | ( the angry tiger ) { e < 3 } '' sentence1 = `` The doog is running in the field '' sentence2 = `` The elephent and the kat '' ... res1 = [ `` the dog '' ] res2 = [ `` e... | Get regex group with fuzziness |
Python | We 've run into a problem with some markdown content . A few jquery editors we used did not write proper markdown syntax . Embedded Links used the 'label ' format , which drops the links at the bottom of the document ( Just like the StackOverflow editor ) . The problem we encountered , is that the links were sometimes ... | This is a sample doucument that would have inline links . [ Example 0 ] [ 0 ] , [ Example 1 ] [ 1 ] , [ Example 2 ] [ 2 ] , [ Example 3 ] [ 3 ] , [ Example 4 ] [ 4 ] [ 0 ] : http : //example.com [ 1 ] : http : //example.com/1 [ 2 ] : http : //example.com/2 [ 3 ] : http : //example.com/3 [ 4 ] : http : //example.com/4 [... | using regex to fix markdown input - link labels |
Python | There are some operations that needs to be done before running some routes . For example : check if we recognise the user , check the language , check the location , set variables in the navbar ( here after named header ) of the htmland so on , then make decisions based on the outcome and lastly run the requested route... | # python3 # /decorator_cookie.pyfrom bottle import request , response , redirectfrom other_module import datamodel , db_pointer , secret_value # custom_moduleimport jsoncookie_value = Nonesurfer_email_exist_in_db = None header = None db_pointer = instanciation_of_a_db_connexion_to_tablessurfer = db_pointer.get ( reques... | bottle : how to set a cookie inside a python decorator ? |
Python | After inputting I get the value However if I enter Decimal ( 1.0/7 ) I get | from decimal import *getcontext ( ) .prec = 6Decimal ( 1 ) / Decimal ( 7 ) Decimal ( ' 0.142857 ' ) Decimal ( ' 0.142857142857142849212692681248881854116916656494140625 ' ) | Why is Python 's Decimal function defaulting to 54 places ? |
Python | Okay I 'm new to OOP , and my problem is that I have this parent class and it has a method info in it.I want to reuse the two print statements within that method for its subclass inside a method of the same name and add more information to it . but I ca n't get it to workI thought of just rewriting the lines of code I ... | class company : def __init__ ( self , fName , lName , salary ) : self.fName = fName self.lName = lName self.salary = salary def info ( self ) : print ( `` Name : '' , self.fName , self.lName ) print ( `` Salary : '' , self.salary ) class programmers ( company ) : def __init__ ( self , fName , lName , salary , progLang ... | how to add contents of a parent class method into a subclass method |
Python | My module has two functions in it : do_something ( ) , and change_behavior ( ) .The function do_something ( ) does Thing A by default . After change_behavior ( ) has been called , do_something ( ) does Thing B instead.I want this transition to be thread-specific . That is , any new thread will have Thing A happen when ... | current_thread = threading.current_thread ( ) setattr ( current_thread , my_reference , new_value ) | Set behavior to be executed when a thread would otherwise finish |
Python | I am creating a number of slices [ -WINDOW-i : -i ] of a list , where i ranges between 32 and 0 : When i == 0 , this returns a slice of length 0 : I do n't want to have to do this to solve it : … because if I have many lists to append to vals , it gets messy.Is there a clean way to do this ? | vals = [ ] for i in range ( 32 , -1 , -1 ) : vals.append ( other_list [ -WINDOW-i : -i ] ) other_list [ -WINDOW-0:0 ] vals = [ ] for i in range ( 32 , -1 , -1 ) : if i == 0 : vals.append ( other_list [ -WINDOW : ] ) else : vals.append ( other_list [ -WINDOW-i : -i ] ) | How to avoid inconsistent s [ i : -j ] slicing behaviour when j is sometimes 0 ? |
Python | I was playing around with clever ways to create a python generator for sequence A003602This appears to work , but I ca n't figure out why . It seems to me like it should hit infinite recursion . Is python doing some lazy evaluation somewhere that I do n't recognize ? To me it seems like since RZ instantly calls the met... | def N ( ) : i=1 while True : yield i i+=1def interleave ( a , b ) : def result ( ) : x=a ( ) y=b ( ) while True : yield next ( x ) yield next ( y ) return resultdef RZ ( ) : return interleave ( N , RZ ) ( ) gen=RZ ( ) | Clever streams-based python program does n't run into infinite recursion |
Python | I am trying to make a program to solve a puzzle an . My attempts work good with sample puzzles I made to test . Now I am trying to make one for a actual puzzle . The puzzle pieces of this new puzzle do n't really have a proper shape . I managed to make the image into black and white and finally in to array of 1s and 0s... | counter = np.zeros ( ( lenX , lenY ) , dtype=int ) for i in range ( lenX ) : for j in range ( lenY ) : if img [ i , j ] ==1 : counter [ i , j ] = count_white ( img , i , j , lenX , lenY ) print ( counter ) tpath = os.getcwd ( ) + '' /test.jpg '' print ( cv2.imwrite ( tpath , Image ) ) print ( `` saved at : `` , tpath )... | find specific points on an image |
Python | Given a string , I need to replace a substring with another in an area not located between two given words.For example : Currently , the only solution I have is extremely unclean:1 ) Replace the string located between the two words to a temporary substring , via Replace a string located between2 ) replace the string I ... | substring : `` ate '' replace to `` drank '' , 1st word - `` wolf '' , 2nd word - `` chicken '' input : The wolf ate the chicken and ate the roosteroutput : The wolf ate the chicken and drank the rooster input a : < < a : b > c > : < a < a < b : b > : b > : b > : aoutput [ a , < < a : b > c > , < a < a < b : b > : b > ... | Python Regex - replace a string not located between two specific words |
Python | I 'm trying to build a list of tiles for a board game from an xml file which contains a description of the tiles . The xml file describes each tile type , and the number of tiles of that type . So far , I 've got the following code which creates a list with exactly one of each tile type : I 'd like to create a list wit... | [ Tile ( el.id ) for el in < tile descriptions > ] [ Tile ( el.id ) * < el.n_tiles > for el in < tile descriptions > ] | Create single list with multiple instances of objects from second list in Python |
Python | I have a DataFrame that looks like this : I want to extract the number from the Dimension column and split it into multiple column : How to do that using the Pandas module in Python ? Thank you ! | |Index| Dimension || -- -- -| -- -- -- -- -- -||0 |1 @ 43X32X34 ||1 |1 @ 120X80X74||2 |2 @ 26X26X32 ||3 |1 @ 120X80X81| |Index| Amount|Length|Width|Height|| -- -- -| -- -- -- -| -- -- -- | -- -- -| -- -- -- ||0 | 1| 43| 32| 34||1 | 1| 120| 80| 74||2 | 2| 26| 26| 32||3 | 1| 120| 80| 81| | How to extract multiple numbers from Pandas Dataframe |
Python | List comprehensions have their code placed directly in the function where they are used , like this : Whereas generator expressions and dict/set comprehensions are mostly placed in a separate nested function , like this : In Python 3 , all of these are placed in a nested function.Why is the code placed in a separate ne... | > > > dis.dis ( ( lambda : [ a for b in c ] ) ) 1 0 BUILD_LIST 0 3 LOAD_GLOBAL 0 ( c ) 6 GET_ITER > > 7 FOR_ITER 12 ( to 22 ) 10 STORE_FAST 0 ( b ) 13 LOAD_GLOBAL 1 ( a ) 16 LIST_APPEND 2 19 JUMP_ABSOLUTE 7 > > 22 RETURN_VALUE > > > dis.dis ( ( lambda : { a for b in c } ) ) 1 0 LOAD_CONST 1 ( < code object < setcomp > ... | Why do generator expressions and dict/set comprehensions in Python 2 use a nested function unlike list comprehensions ? |
Python | I am trying to add a straight line down which would have date printed vertically on the line . I have added a picture of how i am trying to accomplish this below . I have also included the code which i am trying to annotate with.My code : For some reason i am getting warning : But the line is not plotting . Could you a... | import pandas as pdfrom pandas import datetimefrom pandas import DataFrame as dfimport matplotlibfrom pandas_datareader import data as webimport matplotlib.pyplot as pltimport datetimeimport numpy as npstart = datetime.date ( 2015,1,1 ) end = datetime.date.today ( ) start1 = datetime.date ( 2019,1,1 ) data = web.DataRe... | Annoting date on chart |
Python | I have been working with creating some code that I can use in future in order to embed a pygame window within a tkinter window in order to make use of tkinter menus and buttons . I am currently having some issues with dealing with key presses . i want all key presses to be dealt with by pygame rather than tkinter so th... | import pygame , os , _tkinter , systry : import Tkinter as tk BOTH , LEFT , RIGHT , TOP , BOTTOM , X , Y = tk.BOTH , tk.LEFT , tk.RIGHT , tk.TOP , tk.BOTTOM , tk.X , tk.Y two = Trueexcept ImportError : import tkinter as tk from tkinter.constants import * two = Falsefrom pygame.locals import *class PygameWindow ( tk.Fra... | Dispatching keypresses to embedded Pygame |
Python | I am trying to use the next function on an iterator , however , I have a local variable in the same scope that is also named next . The obvious solution is to rename the local variable , however , I 'm fairly new to Python so I 'm curious to learn how to prefix the next function so I achieve the desired behavior.The co... | for prev , curr , next in neighborhood ( list ) : if ( prev == desired_value ) : print ( prev+ '' `` +next ) desired_value = next ( value_iterator ) | Scope of next ( ) in Python |
Python | I need a fast element-wise maximum that compares each row of an n-by-m scipy sparse matrix element-wise to a sparse 1-by-m matrix . This works perfectly in Numpy using np.maximum ( mat , vec ) via Numpy 's broadcasting.However , Scipy 's .maximum ( ) does not have broadcasting . My matrix is large , so I can not cast i... | # Exampleimport numpy as npfrom scipy import sparsemat = sparse.csc_matrix ( np.arange ( 12 ) .reshape ( ( 4,3 ) ) ) vec = sparse.csc_matrix ( [ -1 , 5 , 100 ] ) # Numpy 's np.maximum ( ) gives the **desired result** using broadcasting ( but it ca n't handle sparse matrices ) : numpy_result = np.maximum ( mat.toarray (... | Elementwise maximum of sparse Scipy matrix & vector with broadcasting |
Python | I want a regex that matches any set of digits , with one possible dot . If there is another dot and more digits after it , do an overlapping match with the previous digits , the dot , and the following digits.example string = 'aa323aa232.02.03.23.99aa87..0.111111.mm'desired results = [ 323 , 232.02 , 02.03 , 03.23 , 23... | import rei = 'aa323aa232.02.03.23.99aa87..0.111111.mm'matches = re.findall ( r ' ( ? = ( \d+\ . { 0,1 } \d+ ) ) ' , i ) print matches [ '323 ' , '23 ' , '232.02 ' , '32.02 ' , ' 2.02 ' , '02.03 ' , ' 2.03 ' , '03.23 ' , ' 3.23 ' , '23.99 ' , ' 3.99 ' , '99 ' , '87 ' , ' 0.111111 ' , '111111 ' , '11111 ' , '1111 ' , '11... | Overlapping regex |
Python | An unhashable object can not be inserted into a dict . It is documented , there is good reason for it.However , I do not understand why it affects a membership test : I was assuming that a membership test can return only True or False . But when the value is unhashable , it fails with TypeError : unhashable type . I wo... | if value not in somedict : print ( `` not present '' ) try : result = somedict [ value ] except KeyError : # handle the missing key somedict.get ( value , default ) # args = list of function arguments created from user 's input # where `` V1 '' stands for value1 and `` V2 '' stands for value2XLAT = { 'V1 ' : value1 , '... | unexpected behaviour of dictionary membership check |
Python | I have a very simple package , which I eventually want to release through PyPI , which has a directory tree like the following : parse_date_range.py defines a function called parse.What is the easiest and most pythonic way for me to set up the package for easy importing of the parse function , and how can I do it ? At ... | daterangeparser/ __init__.py parse_date_range.py test.py | Pythonic way to write package for easy importing |
Python | I have a class which contains a list like so : I populate the list of animals with animal objects that have various properties : You can imagine subclasses of Animal that have other properties . I want to be able to write methods that perform the same calculation but on different attributes of the Animal . For example ... | class Zoo : def __init__ ( self ) : self._animals = [ ] class Animal : def __init__ ( self , speed , height , length ) : self._speed = speed self._height = height self._length = length def get_average ( self , propertyname ) : return sum ( getattr ( x , propertyname ) for x in self.animals ) / len ( self.animals ) all_... | Python : object with a list of objects - create methods based on properties of list members |
Python | I know there is an easy , elegant solution to this problem but I am struggling to find it . All I 'm trying to do is add a third column to df2 with the corresponding values from df2 , based on Date and PN . There may be values in df2 that do n't match to df1 , and vice versa ( fill NaN where there is no match ) .df1 : ... | 2017-11-01 2017-11-02 2017-11-03PN 90020 105.0 105.0 105.090022 100.0 100.0 100.0 90061 -3.0 -3.0 -3.0 90065 30.0 30.0 30.090099 2.0 2.0 2.0 PN Date4 90020 2017-11-019 90020 2017-11-0212 90061 2017-11-0113 90065 2017-11-0217 94008 2017-11-03 PN Date Value4 90020 2017-11-01 105.09 90020 2017-11-02 105.012 90061 2017-11-... | Python Pandas - Add values from one dataframe to another by matching labels to columns |
Python | After reading A LOT of data on the subject I still could n't find any actual solution to my problem ( there might not be any ) .My problem is as following : In my project I have multiple drivers working with various hardware 's ( IO managers , programmable loads , power supplies and more ) .Initializing connection to t... | start of code ... with programmable_load ( args ) as program_instance : programmable_load_instance.do_something ( ) rest of code ... class programmable_load ( ) : def __init__ ( self ) : self.handler = handler_creator ( ) def close_connection ( self ) : self.handler.close_connection ( ) self.handler = None def __del__ ... | Guaranteeing calling to destruction on process termination |
Python | My question in brief : given a 1d distribution in Python , how can one identify regions of that distribution that have a sine-like , undulating pattern ? I 'm working to identify images within page scans of historic documents . These images are essentially always full-width within the scans ( that is , they 're basical... | import matplotlib.mlab as mlabimport matplotlib.pyplot as pltfrom scipy.ndimage import imreadimport numpy as npimport sysimg = imread ( sys.argv [ 1 ] ) row_sums = list ( [ ( sum ( r ) /len ( r ) ) for r in img ] ) # the size of the returned array = size of row_sums input arraywindow_size = 150running_average_y = np.co... | Python : Identifying undulating patterns in 1d distribution |
Python | I have the following list which I want to convert into a dictionary.I want to create a dictionary like this : What will be the easiest method to do this ? | newData = [ 'John ' , 4.52 , 'Jane ' , 5.19 , 'Ram ' , 4.09 , 'Hari ' , 2.97 , 'Sita ' , 3.58 , 'Gita ' , 4.1 ] newDict = [ { 'name ' : 'John ' , 'Height ' : 4.52 } , { 'name ' : 'Jane ' , 'Height ' : 5.19 } , { 'name ' : 'Ram ' , 'Height ' : 4.09 } , { 'name ' : 'Hari ' , 'Height ' : 2.97 } , { 'name ' : 'Sita ' , 'He... | How to create a dictionary with new KEY with data from list ? |
Python | Up to now , we manage the crontabs of our servers by hand.I have seen this : http : //django-extensions.readthedocs.org/en/latest/jobs_scheduling.htmlIt is a nice django app , since you just need to edit your crontab once.You enter lines like this once , and for the future a software update is enough , no need to modif... | @ hourly /path/to/my/project/manage.py runjobs hourly | Cronjobs per package |
Python | I have recently started to learn Python and have encountered something a little strange when playing with sets . The following code sample does n't produce the expected results.I expected a_set to have the values { True , 1 , 2 , 3 , 4 } but instead this code produced { True , 2 , 3 , 4 } . Trying variations on this al... | a_set = { True,2,3,4 } a_set.add ( 1 ) a_set = { 1,2,3,4 } a_set.add ( True ) a_set = { False,2,3,4 } a_set.add ( 0 ) a_set = { 0,2,3,4 } a_set.add ( False ) | Adding 1 to a set containing True does not work |
Python | related to why should I make a copy of a data frame in pandasI noticed that in the popular backtesting library , in row 631 . What 's the purpose of such a copy ? | def __init__ ( self , data : pd.DataFrame ) data = data.copy ( False ) | why should I make a *shallow* copy of a dataframe ? |
Python | So I have three Dataframes , X , Y and Events . df_X has X Co-ordinates , df_Y has Y Co-ordinates and Events_df has a list of events that has happened ( The Data is Basketball related ) . You 'll see how they link together by looking below : I want to record patterns of events across time and then take the X , Y coordi... | df_Event : Seconds Passed Event Type Player1.0 Passed The Ball Steve2.0 Received Pass Michael3.0 Touch Michael4.0 Passed The Ball Michael5.0 Received The Ball Georgedf_X : Seconds Passed Steve Michael George1.0 11.43 12.33 15.332.0 11.45 12.46 13.22 3.0 10.99 10.33 14.33 4.0 11.34 10.36 11.225.0 12.43 12.22 11.78df_Y :... | How to BEST extract information from multiple dataframes based on a series of if\else conditions and matching values ? ( Guidance needed ! ) ) |
Python | I 've been searching for a way ( more efficient that just writing loops to traverse the matrix ) to create matrices from elements given in a wrapped diagonal order , and to extract values back out in this order . As an example , given a = [ 2,3,4,5,6,7 ] , I would like to be able to generate the arrayand also be able t... | [ 0 , 2 , 5 , 7 , 0 , 0 , 3 , 6 , 0 , 0 , 0 , 4 , 0 , 0 , 0 , 0 ] | Wrapping/unwrapping a vector along array diagonals |
Python | I have a big python script where multiple print statements and warnings ( e.g . deprecation warnings ) are being printed to the IPython console . For debugging purposes I want to write all print statements and warnings/error to an output file . Is there a way to do this in Spyder ? I have tried in the console ( but it ... | runfile ( 'pyfile.py ' , wdir='wdir ' ) > output.txt python `` directory\pyfile.py '' > output.txt 2 > & 1 | Write print statements including errors/warnings to file in Spyder |
Python | Both of the following code give the same result . But I 'm not sure where should I put the raise statement.Or | def bisection ( f , start , stop , eps = 1e-5 , max_iteration = 100 ) : for __ in range ( max_iteration ) : half = start + ( stop - start ) /2 if abs ( f ( half ) ) < eps or half - start < eps : return half if f ( half ) * f ( start ) > 0 : start = half else : stop = half else : raise ValueError ( ' Can not find root i... | raising an exception in else part of a for loop in Python |
Python | I 'm calculating the euclidean distance between two vectors represented by tuples.The hard-coded way of doing this is pretty fast . However , I would like to make no assumptions about the length of these vectors . That results in solutions like : orwhich turn out to be much ( at least twice ) slower than the first vers... | ( u [ 0 ] -v [ 0 ] ) **2 + ( u [ 1 ] -v [ 1 ] ) **2 + ( u [ 3 ] -v [ 3 ] ) **2 ... sum ( [ ( a-b ) **2 for a , b in izip ( u , v ) ] ) # Faster without generator sum = 0for i in xrange ( len ( u ) ) : sum += ( u [ i ] -v [ i ] ) **2 | Can simple calculations on variable length iterables be made faster in Python ? |
Python | I have a DataFrame similar to the below : , and I want to add a Streak column to it ( see example below ) : The DataFrame is approximately 200k rows going from 2005 to 2020.Now , what I am trying to do is find the number of consecutive games the Home Team has won PRIOR to the date in in the Date column in the DataFrame... | Date Home_Team Away_Team Winner Streak2005-08-06 A G A 02005-08-06 B H H 02005-08-06 C I C 02005-08-06 D J J 02005-08-06 E K K 02005-08-06 F L F 02005-08-13 A B A 1 2005-08-13 C D D 1 2005-08-13 E F F 0 2005-08-13 G H H 02005-08-13 I J J 02005-08-13 K L K 12005-08-20 B C B 02005-08-20 A D A 22005-08-20 G K K 02005-08-2... | Efficiently finding consecutive streaks in a pandas DataFrame column ? |
Python | I have two serializers ... MyRegisterSerializer inherits and extends a popular app/package , django-rest-auth , which connects to a fairly standard user table . I also have a Model and serializer for a custom app , TeamSerializer ( a one-to-many relationship with users ) . When a user signs up , I would like them to be... | class TeamSerializer ( serializers.ModelSerializer ) : class Meta : model = Team fields = ( 'id ' , 'name ' , 'logo ' , 'user ' ) class MyRegisterSerializer ( RegisterSerializer ) : first_name = serializers.CharField ( ) last_name = serializers.CharField ( ) def get_cleaned_data ( self ) : super ( MyRegisterSerializer ... | Combining serializer and model functions |
Python | In the full python grammar specification with statement is defined as : Where expr is : Why does with_item contains expr rule instead of plain name ? This is valid python code : According to the grammar this code is also valid ? | with_stmt : 'with ' with_item ( ' , ' with_item ) * ' : ' suitewith_item : test [ 'as ' expr ] expr : xor_expr ( '| ' xor_expr ) *xor_expr : and_expr ( '^ ' and_expr ) *and_expr : shift_expr ( ' & ' shift_expr ) * with open ( '/dev/null ' ) as f : pass with open ( '/dev/null ' ) as x^y|z : pass | Python grammar : with_stmt |
Python | In the following python script , why the second assert goes through ( i.e. , when adding 0 to 257 and stores the result in y , then x and y become different objects ) ? Thanks ! | x = 257y = 257assert x is yx = 257 y = 257 + 0assert x is not y | Python integer caching |
Python | Consider the following example : Here , after the breakpoint is entered , the debugger does n't have access to the exception instance bound to err : Why is this the case ? How can I access the exception instance ? Currently I 'm using the following workaround but it feels awkward : Interestingly , using this version , ... | try : raise ValueError ( 'test ' ) except ValueError as err : breakpoint ( ) # at this point in the debugger , name 'err ' is not defined $ python test.py -- Return -- > test.py ( 4 ) < module > ( ) - > None- > breakpoint ( ) ( Pdb ) p err*** NameError : name 'err ' is not defined try : raise ValueError ( 'test ' ) exc... | breakpoint in except clause does n't have access to the bound exception |
Python | I want to make visiting websites much faster with Selenium . Does someone know , What I can do here ? I already know that I should switch off Javascript or images , for example , but what else is there ? Here is my code . You can ignore the fact that I am using the Tor Browser ( that is why it is very slow ) : Can anyo... | from selenium import webdriverfrom selenium.webdriver.firefox.firefox_profile import FirefoxProfilefrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECtorexe = os.popen ( r ' C : \Users\Max\Desktop\Tor_Browser\Browser\TorBrowser\Tor\tor.exe ' ) profile ... | What options are there to make visiting a website faster with Selenium and Tor browser ? |
Python | On my computer , I can check thatevaluates to False.More generally , I can estimate that the formula ( a + b ) + c == a + ( b + c ) fails roughly 17 % of the time when a , b , c are chosen uniformly and independently on [ 0,1 ] , using the following simulation : I wonder if it is possible to arrive at this probability ... | ( 0.1 + 0.2 ) + 0.3 == 0.1 + ( 0.2 + 0.3 ) import numpy as npimport numexprnp.random.seed ( 0 ) formula = ' ( a + b ) + c == a + ( b + c ) 'def failure_expectation ( formula=formula , N=10**6 ) : a , b , c = np.random.rand ( 3 , N ) return 1.0 - numexpr.evaluate ( formula ) .mean ( ) # e.g . 0.171744 import pandas as p... | Probability that a formula fails in IEEE 754 |
Python | I have a pandas dataframe df : I want to transform this datafarme ( DF ) based on values in the list ( values ) . In df , first number 250 . It is between 200 and 400 in list values , such that ( |200-250| ) / ( 400-200 ) = 0.25 and ( 400-250 ) / ( 400-200 ) =0.75 , respectively . If data is missing ( np.nan ) then row... | import pandas as pdimport numpy as npdata = { ' A ' : [ 250,100,400 , np.nan,300 ] } df = pd.DataFrame ( data ) print ( df ) A0 250.01 100.02 400.03 NaN4 300.0 values = [ 0,200,400,600 ] 0 200 400 6000 0.0 0.25 0.75 0.01 0.5 0.50 0.00 0.02 0.0 0.00 1.00 0.03 0.0 0.00 0.00 0.04 0.0 0.50 0.50 0.0 | pandas int or float column to percentage distribution |
Python | I am trying to roll up daily data into fiscal quarter data . For example , I have a table with fiscal quarter end dates : and a table of daily data : And I would like to create the table below.However , I do n't know how to group by varying dates without looping through each record . Any help is greatly appreciated.Tha... | Company Period Quarter_EndM 2016Q1 05/02/2015M 2016Q2 08/01/2015M 2016Q3 10/31/2015M 2016Q4 01/30/2016WFM 2015Q2 04/12/2015WFM 2015Q3 07/05/2015 WFM 2015Q4 09/27/2015WFM 2016Q1 01/17/2016 Company Date PriceM 06/20/2015 1.05M 06/22/2015 4.05M 07/10/2015 3.45M 07/29/2015 1.86M 08/24/2015 1.58M 09/02/2015 8.64M 09/22/2015... | How to group pandas DataFrame by varying dates ? |
Python | I tried using set ( ) method of python to find the unique elements in the List . It works fine removing all the duplicates . But here is my requirement , I want to get the elements which are removed by using set ( ) method . Could any one please assist me in this ? My expected output is [ 1 ] .The element which is remo... | a= [ 1,2,3,1,4 ] b=set ( a ) Output : [ 1,2,3,4 ] | How to Identify the elements which are removed from set ( ) in python ? |
Python | For example , in the following code : Python would automatically print 'hi ' . Sorry if this is an obvious question , but I ca n't find out why Python would do that unless a 'test ' object was initiated . * I just started programming in general a few months ago and Python is my first language , so please spare some mer... | class test : print `` Hi '' | Why does a class get `` called '' when not initiated ? - Python |
Python | I have an int-derived class with overloaded comparison operator.In the body of the overloaded methods I need to use the original operator.The toy example : works fine with Python 3.3+ , but fails with Python 2.7 with exception AttributeError : 'super ' object has no attribute '__eq__'.I can think about several walkarro... | > > > class Derived ( int ) : ... def __eq__ ( self , other ) : ... return super ( Derived , self ) .__eq__ ( other ) return int ( self ) == other try : return super ( Derived , self ) .__eq__ ( other ) except AttributeError : return super ( Derived , self ) .__cmp__ ( other ) == 0 | Accessing original int comparison from int-derived class with overloaded comparison operator |
Python | I 'm trying to fetch some tabular content from a webpage using the script below . To populate the content manually , it is necessary to choose the options from the dropdown shown in this image before hitting the Submit button . I 've tried to mimic the post http requests accordingly . However , I might have gone somewh... | import requestsfrom bs4 import BeautifulSoupURL = 'https : //www.lgindiasocial.com/microsites/brand-store-web-five/locate.aspx'headers = { ' x-microsoftajax ' : 'Delta=true ' , 'origin ' : 'https : //www.lgindiasocial.com ' , 'content-type ' : 'application/x-www-form-urlencoded ; charset=UTF-8 ' , 'referer ' : 'https :... | Ca n't parse tabular content from some search results using post requests |
Python | The excel file generated can not be open when my project started with uwsgi when lxml installed in my environment as it can be opened successfully with django manage.py runserver and gunicornMy main codes like below : urls.py wsgi.py test_excel.iniThen if i start the project like uwsgi -- ini test_excel.ini as lxml ins... | ── test_excel ├── urls.py ├── wsgi.py └── settings.py── manage.py from django.contrib import adminfrom django.urls import pathfrom django.views import Viewfrom openpyxl.writer.excel import save_virtual_workbookimport pandas as pdfrom django.http import HttpResponse , StreamingHttpResponseimport xlrdimport openpyxlfrom ... | lxml + django + uwsgi failed to generate a right format excel file? |
Python | A generator-returning function ( i.e . one with a yield statement in it ) in one of our libraries fails some tests due to an unhandled StopIteration exception . For convenience , in this post I 'll refer to this function as buggy.I have not been able to find a way for buggy to prevent the exception ( without affecting ... | # mymod.pyimport csv # essential ! def buggy ( csvfile ) : with open ( csvfile ) as stream : reader = csv.reader ( stream ) # how to test *here* if either stream is at its end ? for row in reader : yield row # ! /usr/bin/env python3 # myscript.pyimport sysimport mymoddef print_row ( row ) : print ( *row , sep='\t ' ) d... | How can I prevent or trap StopIteration exception in the yield-calling function ? |
Python | I would like to visualize the number of required machines in a jobshop at a certain time in graph with on the x-axis a continuous time axis and on the y-axis the number of shifts . In the dataframe below , you find an example of my data . Here , you see Shift_IDs ( which are unique ) and the start and end time of that ... | df : Shift_ID Shift_Time_Start Shift_Time_End0 1 2016-03-22 9:00:00 2016-03-22 9:35:001 2 2016-03-22 9:20:00 2016-03-22 10:20:002 3 2016-03-22 9:40:00 2016-03-22 10:14:003 4 2016-03-22 10:00:00 2016-03-22 10:31:00 df2 : Interval Count0 2016-03-22 9:00:00 - 2016-03-22 9:15:00 11 2016-03-22 9:15:00 - 2016-03-22 9:30:00 2... | Calculate required equipment on shifts in timespans |
Python | With a list containing some missing values such as this : How can you subset the values that are positioned between two missing ( nan ) values ? I know how to do it with a for loop : Any suggestions on how to do this in a less cumbersome way ? | [ 10 , 11 , 12 , np.nan , 14 , np.nan , 16 , 17 , np.nan , 19 , np.nan ] # importsimport numpy as np # inputlst= [ 10,11,12 , np.nan , 14 , np.nan , 16 , 17 , np.nan , 19 , np.nan ] # define an empty list and build on that in a For Loopsubset= [ ] for i , elem in enumerate ( lst ) : if np.isnan ( lst [ i-1 ] ) and np.i... | How to subset list elements that lie between two missing values ? |
Python | This question is making me pull my hair out.if I do : and call it from one thousand threads , how does the generator knows what to send next for each thread ? Everytime I call it , does the generator save a table with the counter and the caller reference or something like that ? It 's weird . Please , clarify my mind o... | def mygen ( ) : for i in range ( 100 ) : yield i | How Python Generators know who 's calling ? |
Python | In the mathematical sense , a set ( or type ) is closed under an operation if the operation always returns a member of the set itself.This question is about making a class that is closed under all operations inherited from its superclasses.Consider the following class.Since __add__ has not been overridden , it is not c... | class MyInt ( int ) : pass x = MyInt ( 6 ) print ( type ( x + x ) ) # < class 'int ' > import functoolsclass ClosedMeta ( type ) : _register = { } def __new__ ( cls , name , bases , namespace ) : # A unique id for the class uid = max ( cls._register ) + 1 if cls._register else 0 def tail_cast ( f ) : @ functools.wraps ... | How to create a type that is closed under inherited operations ? |
Python | if arr = [ 4,3,2,1 ] and i want to swap the first value with the minimum of the array , if am using this on python they are not working but if i do thisthis works fine . Can anyone explain why ? | arr [ 0 ] , arr [ arr.index ( min ( arr ) ) ] = min ( arr ) , arr [ 0 ] # or arr [ 0 ] , arr [ arr.index ( min ( arr ) ) ] = arr [ arr.index ( min ( arr ) ) ] , arr [ 0 ] b = arr.index ( min ( arr ) ) # and then arr [ 0 ] , arr [ b ] = arr [ b ] , arr [ 0 ] | Swapping list elements in python where the expressions contain function calls |
Python | I am new to Python and trying to generate 5 numbers with 2 conditions : There must be 3 even and 2 odd numbersFrom those 5 numbers 3 must be low ( 1,51 ) and 2 high ( 51,100 ) . Which number will be low or high is not of interest.I have managed to solve the first part : Obviously this is not getting me anywhereFor the ... | import randomrand_even = random.sample ( range ( 0 , 100 , 2 ) , 3 ) rand_odd = random.sample ( range ( 1 , 100 , 2 ) , 2 ) rand_total = rand_even , rand_oddprint ( rand_total ) rand_low = random.sample ( range ( 0 , 51 ) , 3 ) rand_high = random.sample ( range ( 51,100 ) , 2 ) | Random number generator with conditions - Python |
Python | I am new to python . I have the following data frame . I am able to pivot in Excel.I want to add the difference column ( in the image , I added it manually ) .The difference is B-A value . I am able to replicate except difference column and Grand Total using Python pivot table . Below is my code.How can I add the diffe... | table = pd.pivot_table ( data , index= [ 'Category ' ] , values = [ 'value ' ] , columns= [ 'Name ' , 'Date ' ] , fill_value=0 ) df = pd.DataFrame ( { `` Value '' : [ 0.1 , 0.2 , 3 , 1 , -.5 , 4 ] , '' Date '' : [ `` 2020-07-01 '' , `` 2020-07-01 '' , `` 2020-07-01 '' , `` 2020-07-01 '' , `` 2020-07-01 '' , `` 2020-07-... | Python pivot_table - Add difference column |
Python | I am doing car tracking on a video . I am trying to determine how many meters it traveled.I randomly pulled 7 points from a video frame . I made point1 as my originThen on the corresponding Google Maps perspective , I calcculated the distances of the 6 points from the orgin ( delta x and delta y ) Then I ran the follow... | pts_src = np.array ( [ [ 417 , 285 ] , [ 457 , 794 ] , [ 1383 , 786 ] , [ 1557 , 423 ] , [ 1132 , 296 ] , [ 759 , 270 ] , [ 694 , 324 ] ] ) pts_dst = np.array ( [ [ 0,0 ] , [ -3 , -31 ] , [ 30 , -27 ] , [ 34 , 8 ] , [ 17 , 15 ] , [ 8 , 7 ] , [ 6 , 1 ] ] ) h , status = cv2.findHomography ( pts_src , pts_dst ) a = np.arr... | finding the mapping between video point and real world point |
Python | I 'd like to be able to open a Python shell , execute some code defined in a module , then modify the module , then re-run it in the same shell without closing/reopening.I 've tried reimporting the functions/objects after modifying the script , and that does n't work : Clearly reimporting did not get me the 'new versio... | Python 2.7.2 ( default , Jun 20 2012 , 16:23:33 ) [ GCC 4.2.1 Compatible Apple Clang 4.0 ( tags/Apple/clang-418.0.60 ) ] on darwinType `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > from my_module import buggy_function , test_input > > > buggy_function ( test_input ) wrong_val... | Run code from a Python module , modify module , then run again without exiting interpeter |
Python | I have two 2D numpy arrays ( simplified in this example with respect to size and content ) with identical sizes.An ID matrix : and a value matrix : My goal is to count and sum the values from the second matrix grouped by the IDs from the first matrix : I can do this in a for loop but when the matrices have sizes in tho... | 1 1 1 2 21 1 2 2 51 1 2 5 51 2 2 5 52 2 5 5 5 14.8 17.0 74.3 40.3 90.225.2 75.9 5.6 40.0 33.778.9 39.3 11.3 63.6 56.711.4 75.7 78.4 88.7 58.679.6 32.3 35.3 52.5 13.3 1 : ( 8 , 336.8 ) 2 : ( 9 , 453.4 ) 5 : ( 8 , 402.4 ) | Summing data from array based on other array in Numpy |
Python | I have a program that finds the highest and lowest values in an array , excludes them , then sums up the rest of the numbers in that array . It works with most random inputs , except for cases when there are duplicates of the highest or the lowest number in that arrayIn which case if I print ( sum_array ( [ 6 , 0 , 1 ,... | def sum_array ( arr ) : if arr is None : return 0 if len ( arr ) < 2 : return 0 return sum ( [ i for i in arr if i ! = max ( arr ) and i ! = min ( arr ) ] ) | Sum of an array while ignoring one minimum and one maximum |
Python | Just wanted to ask why this ( list comprehension , if I 'm not mistaken ) : is twice as fast ( 108 steps on visualize python ) as this ( 202 steps ) : ? And also , although the first code is faster , does the second code have any advantages in any cases ? Maybe , uses less memory ? Just spitballing , don '' t really ha... | def s ( number ) : return sum ( [ n for n in range ( number ) if n % 3==0 or n % 5==0 ] ) s ( 100 ) def s ( number ) : return sum ( n for n in range ( number ) if n % 3==0 or n % 5==0 ) s ( 100 ) | Python quick question about comprehensions vs list comprehensions |
Python | Given a replacement map like { search : replace , search : replace , ... } and a string , how to generate a list of all possible replacements of that string ( first substring replaced , second substring replaced , both replaced etc ) . Example : The order is not important . | map = { 'bee ' : 'BETA ' , 'zee ' : 'ZETA ' , 'dee ' : 'DELTA ' } source_string = 'bee foo zee bar bee'desired result = [ 'bee foo zee bar bee ' , 'BETA foo zee bar bee ' , 'bee foo ZETA bar bee ' , 'BETA foo ZETA bar bee ' , 'bee foo zee bar BETA ' , 'BETA foo zee bar BETA ' , 'bee foo ZETA bar BETA ' , 'BETA foo ZETA... | Generate all possible replacements |
Python | required output : Above is the code I have been trying but it gives an error zip argument # 1 must support iteration | d = { ' a ' : [ [ 1 , 2 , 3 ] , [ 1 , 2 , 3 ] ] , ' b ' : [ [ 2 , 4 , 1 ] , [ 1 , 6 , 1 ] ] , } def add_element ( lst ) : ad = [ sum ( i ) for i in zip ( *lst ) ] return addef csv_reducer2 ( dicty ) : return { k : list ( map ( add_element , v ) ) for k , v in dicty.items ( ) } csv_reducer2 ( d ) { ' b ' : [ 3 , 10 , 2 ... | Summation of elements of dictionary that are list of lists |
Python | Im new to python and trying to work on looping through data : I am using the sendgrid api global stats endpoint and I am successful in getting my output for one API key.My code : Output : However , this is the output of one API key . I have several API keys under the same account and have different data associated with... | import pandas as pdimport jsonfrom pandas.io.json import json_normalizefrom datetime import datetoday = date.today ( ) .strftime ( ' % Y- % m- % d ' ) import http.clientconn = http.client.HTTPSConnection ( `` api.sendgrid.com '' ) payload = `` { } '' headers = { 'authorization ' : `` Bearer SG.FO0*** '' } conn.request ... | How do I loop through API keys to get output for them in separate rows in my final dataframe ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.