lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | Say I have a dataframe containing strings , such as : I 'm looking for a way to apply a rolling window on col1 and join the strings in a certain window size . Say for instance window=3 , I 'd like to obtain ( with no minimum number of observations ) : I 've tried the obvious solutions with rolling which fail at handlin... | df = pd.DataFrame ( { 'col1 ' : list ( 'some_string ' ) } ) col10 s1 o 2 m3 e4 _5 s ... col10 s1 so2 som3 ome4 me_5 e_s6 _st7 str8 tri9 rin10 ing df.col1.rolling ( 3 , min_periods=0 ) .sum ( ) df.col1.rolling ( 3 , min_periods=0 ) .apply ( `` .join ) | Rolling sum with strings |
Python | I have a setup.py file that is very similar to the one shown here : https : //stackoverflow.com/a/49866324/4080129 . It looks like this : There 's a package with some pure-Python , and a submodule that contains Cython files . The setup.py is in the parent folder , not in the Cython one : Now , setup.py correctly compil... | from distutils.core import setup , Extensionfrom Cython.Build import cythonizeimport numpysources = [ `` hs/subfolder/detect.pyx '' , `` hs/subfolder/Donline.cpp '' , `` hs/subfolder/Handler.cpp '' , `` hs/subfolder/Process.cpp '' , `` hs/subfolder/Filter.cpp '' , `` hs/subfolder/Localize.cpp '' ] exts = [ Extension ( ... | Cython attemps to compile twice , and fails |
Python | I have a django 1.9.2 project using Django Rest Framework JSON API : https : //github.com/django-json-api/django-rest-framework-json-api : My viewset looks like this : Typical response looks like this : I want the output to have a data attribute as opposed to the results attribute . How can I tell DRF JSON API to outpu... | class QuestionViewSet ( viewsets.ReadOnlyModelViewSet ) : `` '' '' API endpoint that allows questions and answers to be read. `` '' '' resource_name = 'questions ' queryset = Question.objects.all ( ) serializer_class = QuestionSerializer renderers = renderers.JSONRenderer parsers = parsers.JSONParser { `` links '' : { ... | How to generate JSON-API data attribute vs results attribute in Django Rest Framework JSON API ? |
Python | Suppose I have an array which is NxNxN and I want to create an averaged array which stacks each direction . x-y ( averaged over z ) , x-z ( averaged over y ) , y-z ( averaged over x ) For x-y I would do : Do I simply use axis=1 [ or 2 or 3 ] to stack it in each direction ? | np.mean ( data , axis=1 , dtype=np.float64 ) | getting x , y , z , mean through a 3D data array |
Python | I 'm trying to make a game engine in Python as a `` weekend project '' but I have a problem.I 'm trying to make it that a user can declare a keybind by typing the key and the function into a text file what they want to run but when I run the code from that sheet with exec it runs the function and I have no idea on how ... | for line in bind : try : exec line except : try : error.write ( localtime + `` : `` + `` ERROR : Could not bind key from the bind file : `` + line ) except : pass _w = Functions.motion.move ( ) .forward ( ) _a = Functions.motion.move ( ) .left ( ) _s = Functions.motion.move ( ) .back ( ) _d = Functions.motion.move ( ) ... | Call a function through a variable in Python |
Python | Don ’ t mix up apples and orangesThe problemI ’ m playing with the __eq__ operator and the NotImplemented value.I ’ m trying to understand what ’ s happen when obj1.__eq__ ( obj2 ) returns NotImplemented and obj2.__eq__ ( obj1 ) also returns NotImplemented.According to the answer to Why return NotImplemented instead of... | class Apple ( object ) : def __init__ ( self , color ) : self.color = color def __repr__ ( self ) : return `` < Apple color= ' { color } ' > '' .format ( color=self.color ) def __eq__ ( self , other ) : if isinstance ( other , Apple ) : print ( `` { self } == { other } - > OK '' .format ( self=self , other=other ) ) re... | Why is NotImplemented evaluated multiple times with __eq__ operator |
Python | I ca n't figure out why the following code is makes fib run in linear rather than exponential time.For example , fib ( 100 ) does n't completely blow up like I expected it to.My understanding is that @ memoize sets fib = memoize ( fib ) . So when you call fib ( 100 ) , seeing that 100 is not in the cache , it will call... | def memoize ( obj ) : `` '' '' Memoization decorator from PythonDecoratorLibrary . Ignores **kwargs '' '' '' cache = obj.cache = { } @ functools.wraps ( obj ) def memoizer ( *args , **kwargs ) : if args not in cache : cache [ args ] = obj ( *args , **kwargs ) return cache [ args ] return memoizer @ memoizedef fib ( n )... | Why does this memoizer work on recursive functions ? |
Python | I have a python script using a cython module I wrote . I want to publish it , and in order to save users the trouble of compiling the cython stuff ( especially complex on Windows ) , I want to provide pre-compiled extensions.However , I will need one version for 32 bits and another for 64 . I thought about including th... | if bits == 32 : from mymodule32 import *elif bits == 64 : from mymodule64 import * | How to provide pre-compiled cython modules for 32 and 64 bits neatly ? |
Python | i 'm doing a matrix calculation using pandas in python.my raw data is in the form of list of strings ( which is unique for each row ) .i have to do a calculate a score with one row and against all the other rowsscore calculation algorithm : repeat step 2,3 between id 0 and id 1,2,3 , similarly for all the ids.Create N ... | id list_of_value0 [ ' a ' , ' b ' , ' c ' ] 1 [ 'd ' , ' b ' , ' c ' ] 2 [ ' a ' , ' b ' , ' c ' ] 3 [ ' a ' , ' b ' , ' c ' ] Step 1 : Take value of id 0 : [ ' a ' , ' b ' , ' c ' ] , Step 2 : find the intersection between id 0 and id 1 , resultant = [ ' b ' , ' c ' ] Step 3 : Score Calculation = > resultant.size / id... | pandas matrix calculation till the diagonal |
Python | I am doing a ( typical ) assignment of finding primes . I thought I 'd be clever and , for large numbers , skip the division process with this trick : Adding 5 to itself a few thousand times seems like a waste ( I only need the last member ) , but I wanted to be sure.credit to unutbu on Measure time elapsed in Python ?... | def div5 ( candidate ) : return str ( candidate ) [ -1 ] == `` 5 '' % > python -mtimeit -s '' import intDiv '' `` intDiv.div5 ( 2147483645 ) '' 1000000 loops , best of 3 : 0.272 usec per loop % > python -mtimeit -s '' import strDiv '' `` strDiv.str5 ( 2147483645 ) '' 1000000 loops , best of 3 : 0.582 usec per loop def ... | Why is large integer division faster than slicing ( numeric ) strings , for accessing individual digits ? |
Python | I have created a python code that solves a group lasso penalized linear model . For those of you not used to work with these models , the basic idea is that you give as input a dataset ( x ) and a response variable ( y ) , as well as the value of a parameter ( lambda1 ) , varying the value of this parameter changes the... | # -*- coding : utf-8 -*-from __future__ import divisionimport functoolsimport multiprocessing as mpimport numpy as npfrom cvxpy import *def lm_gl_preprocessing ( x , y , index , lambda1=None ) : lambda_vector = [ lambda1 ] m = x.shape [ 1 ] n = x.shape [ 0 ] lambda_param = Parameter ( sign= '' positive '' ) m = m+1 ind... | Difference of solution between sequential and parallel programming |
Python | I have n ordered lists of unequal size ( where I do not know beforehand how many lists there are going to be ) . I need to find the minimum average distance between one element in each list.For example given n=3 for three lists : The output should be ( 22,23,24 ) because : which is the smallest among all the points in ... | a = [ 14 , 22 , 36 , 48 ] b = [ 14 , 23 , 30 , 72 ] c = [ 1 , 18 , 24 ] mean ( abs ( 22-23 ) , abs ( 23-24 ) , abs ( 22-24 ) ) = 1.33333 def aligner ( aoa ) : ' '' read arrays of arrays of peaks and return closest peaks '' ' # one of arrays is emptyif not [ y for x in aoa for y in x ] : return None # there is the same ... | Algorithm , closest point between list elements |
Python | There 's a ifconfig sphinx extension -- and it allows for conditional inclusion of content . I 'm looking for a way to conditionally include extensions . My best try is just to give a list of extensions with a -D option to sphinx-build : but it does n't work.The problem is to conditionally include sphinx.ext.htmlmath o... | sphinx-build -b singlehtml -d _build/doctrees -D html_theme=empty -D `` extensions= [ 'sphinx.ext.autodoc ' , 'sphinx.ext.viewcode ' , 'sphinx.ext.numfig ' , 'sphinx.ext.ifconfig ' , 'cloud_sptheme.ext.table_styling ' , 'sphinx.ext.htmlmath ' ] '' . _build/wkA | Conditionally include extensions ? |
Python | This is a fairly straightforward question hopefully you all can enlighten me . In the example below how do I define __repr__ to be dynamically set to self.name ? Thanks all ! What I am looking for is thispsuedo code | import reinputlist = 'Project= '' Sparcy '' Desc= '' '' \nProject= '' Libs '' Desc= '' '' \nProject= '' Darwin '' Desc= '' '' \nProject= '' Aaple '' Desc= '' The big project '' 'regex = re.compile ( ' ( [ ^ = ] + ) *= * ( `` [ ^ '' ] * '' | [ ^ ] * ) ' ) results = [ ] for project in inputlist.split ( `` \n '' ) : items... | Dynamically creating classes in python and __repr__ |
Python | Consider the following series , serHow to count the values such that every consecutive number is counted and returned ? Thanks . | date id 2000 NaN2001 NaN 2001 12002 12000 22001 22002 22001 NaN2010 NaN2000 12001 12002 12010 NaN CountNaN 2 1 2 2 3NaN 21 3NaN 1 | How to count consecutive repetitions in a pandas series |
Python | A question of particular interest about python for loops . Engineering programs often require values at previous or future indexes , such as : etc ... However I rather like the nice clean python syntax : or for a list of 2d point data : I like the concept of looping over a list without explicitly using an index to refe... | for i in range ( 0 , n ) : value = 0.3*list [ i-1 ] + 0.5*list [ i ] + 0.2*list [ i+1 ] for item in list : # Do stuff with item in list for [ x , y ] in list : # Process x , y data | Referencing list entries within a for loop without indexes , possible ? |
Python | Lately , I 've been adding asserts to nearly every single function I make to validate every input as sort of a poor-man 's replacement for type checking or to prevent myself from accidentally inputting malformed data while developing . For example , However , I 'm worried that this goes against the idea of duck typing ... | def register_symbol ( self , symbol , func , keypress=None ) : assert ( isinstance ( symbol , basestring ) ) assert ( len ( symbol ) == 1 ) assert ( callable ( func ) ) assert ( keypress is None or type ( keypress ) is int ) self.symbols_map [ symbol ] = ( func , keypress ) return | Can you have too many asserts ( in Python ) ? |
Python | If I have an element I 'm trying to get from a dictionary : my_dict [ i ] [ 'level_1 ' ] [ 'level_2 ' ] [ 'my_var ' ] .Is there a cleaner way than doing this to check for nulls ? | if 'level_1 ' in my_dict [ i ] : if 'level_2 ' in my_dict [ i ] [ 'level_1 ' ] : if 'my_var ' in my_dict [ i ] [ 'level_1 ' ] [ 'level_2 ' ] : my_var = my_dict [ i ] [ 'level_1 ' ] [ 'level_2 ' ] [ 'my_var ' ] | Is there a clean test for a dictionary element in Python ? |
Python | I have been having trouble with Python mock and have been going crazy . I 've held off on this question due to fear of down voting for not enough research . I have a cumulative 24 hours over the last week trying to figure out how to get this work and can not .I have read numerous examples and have created this one from... | # ExampleModule.pyimport requestsimport urllib2def hello_world ( ) : try : print `` BEGIN TRY '' r = requests.request ( 'GET ' , `` http : //127.0.0.1:80 '' ) print r.ok if r.ok : print `` PATCH 1 FAILED '' else : print `` PATCH 1 SUCCESSFUL '' except urllib2.HTTPError : print `` PATCH 2 SUCCESSFUL '' print `` EXCEPTIO... | To Kill A Mocking Object : A Python Story |
Python | OS : debian9.A simple multi-processes program named mprocesses.py.Run python3 mprocesses.py and get below output.Get processes info.Check processes tree view.What confused me is the three threads 6148,6149,6150.Does that mean every process contain one process ? Maybe my logical graph is better to express relationships ... | import osimport multiprocessingdef run_task ( name ) : print ( `` task % s ( pid = % s ) is running '' % ( name , os.getpid ( ) ) ) while True : passif __name__ == `` __main__ '' : print ( `` current process % s . '' % os.getpid ( ) ) pool = multiprocessing.Pool ( processes = 2 ) for i in range ( 2 ) : pool.apply_async... | The relationship between thread and process in multi-process program |
Python | How to get previous or next object with this format of code ? I know how to do that with : | alignment = [ [ a , b , c ] , [ 2,3,4 ] , [ q , w , e ] ] for obj in alignment : some code here to get previous object for i in range ( 0 , len ( alignment ) ) : alignment [ i-1 ] [ objIndex ] | Get previous object without len ( list ) |
Python | The following will make more sense if you have ever played minecraft . Since many of you have not , I will try to explain it as best as I canI am trying to write a recursive function that can find the steps to craft any minecraft item from a flatfile of minecraft recipes . This one has me really stumped.The flatfile is... | def getRecipeChain ( item , quantity=1 ) : # magic recursive stuffs go here def getRecipeChain ( name , quantity=1 ) : chain = [ ] def getRecipe ( name1 , quantity1=1 ) : if name1 in recipes : for item in recipes [ name1 ] [ `` ingredients '' ] [ `` input '' ] : if item in recipes : getRecipe ( item , quantity1 ) else ... | Python Recursive Data Reading |
Python | I have a matrix M with values 0 through N within it . I 'd like to unroll this matrix to create a new matrix A where each submatrix A [ i , : , : ] represents whether or not M == i.The solution below uses a loop.This yields : Is there a faster way , or a way to do it in a single numpy operation ? | # Example Setupimport numpy as npnp.random.seed ( 0 ) N = 5M = np.random.randint ( 0 , N , size= ( 5,5 ) ) # Solution with LoopA = np.zeros ( ( N , M.shape [ 0 ] , M.shape [ 1 ] ) ) for i in range ( N ) : A [ i , : , : ] = M == i Marray ( [ [ 4 , 0 , 3 , 3 , 3 ] , [ 1 , 3 , 2 , 4 , 0 ] , [ 0 , 4 , 2 , 1 , 0 ] , [ 1 , 1... | How to efficiently unroll a matrix by value with numpy ? |
Python | This question is about boosting Pandas ' performance during stacking and unstacking operation . The issue is that I have a large dataframe ( ~2GB ) . I followed this blog to compress it to ~150MB successfully . However , my stacking and unstacking operation take infinite amount of time such that I have to kill the kern... | import pandas as pd # Added code to generate test datadata = { 'ANDroid_Margin ' : { 'type ' : 'float ' , 'len':13347 } , 'Name ' : { 'type ' : 'cat ' , 'len':71869 } , 'Geo1 ' : { 'type ' : 'cat ' , 'len':4 } , 'Geo2 ' : { 'type ' : 'cat ' , 'len':31 } , 'Model ' : { 'type ' : 'cat ' , 'len':2 } } ddata_i = pd.DataFra... | pandas stack and unstack performance reduces after dataframe compression and is much worse than R 's data.table |
Python | I have a function that has a few possible return values . As a trivial example , let 's imagine it took in a positive int and returned `` small '' , `` medium '' , or `` large '' : I am wondering the best way to write & define the return values . I am wondering about using Python function attributes , as follows : Then... | def size ( x ) : if x < 10 : return SMALL if x < 20 : return MEDIUM return LARGE def size ( x ) : if x < 10 : return size.small if x < 20 : return size.medium return size.largesize.small = 1size.medium = 2size.large = 3 if size ( n ) == size.small : ... | Python -- using function attributes as return values |
Python | Is there are difference between random ( ) * random ( ) and random ( ) ** 2 ? random ( ) returns a value between 0 and 1 from a uniform distribution.When testing both versions of random square numbers I noticed a little difference . I created 100000 random square numbers and counted how many numbers are in each interva... | from random import randomlst = [ 0 for i in range ( 100 ) ] lst2 , lst3 = list ( lst ) , list ( lst ) # create two random distributions for random ( ) * random ( ) for i in range ( 100000 ) : lst [ int ( 100 * random ( ) * random ( ) ) ] += 1for i in range ( 100000 ) : lst2 [ int ( 100 * random ( ) * random ( ) ) ] += ... | Why is random ( ) * random ( ) different to random ( ) ** 2 ? |
Python | I have a list of unequal lists.I would like to generate a new list with list comprehension from the sublists.I am trying the following code but it keeps raising an indexError : The expected output would be : Any ideas how to get this to work ? | s = [ [ ' a ' , ' b ' , ' c ' , 'd ' ] , [ ' e ' , ' f ' , ' g ' ] , [ ' h ' , ' i ' ] , [ ' j ' , ' k ' , ' l ' , 'm ' ] ] new_s = [ ] for i in range ( len ( s ) ) : new_s.append ( ( i , [ t [ i ] for t in s if t [ i ] ) ) new_s = [ ( 0 , [ ' a ' , ' e ' , ' h ' , ' j ' ] ) , ( 1 , [ ' b ' , ' f ' , ' i ' , ' k ' ] ) ... | How to make a list comprehension in python with unequal sublists |
Python | I have 2 lists like this : and I want to obtain a list l3 , which is a join of l1 and l2 where values of ' a ' and ' b ' are equal in both l1 and l2i.e.How can I do this ? | l1 = [ { ' a ' : 1 , ' b ' : 2 , ' c ' : 3 , 'd ' : 4 } , { ' a ' : 5 , ' b ' : 6 , ' c ' : 7 , 'd ' : 8 } ] l2 = [ { ' a ' : 5 , ' b ' : 6 , ' e ' : 100 } , { ' a ' : 1 , ' b ' : 2 , ' e ' : 101 } ] l3 = [ { ' a ' : 1 , ' b : 2 , ' c ' : 3 , 'd ' : 4 , ' e ' : 101 } , { ' a ' : 5 , ' b : 6 , ' c ' : 7 , 'd ' : 8 , ' e... | How to join 2 lists of dicts in python ? |
Python | For this question , I refer to the example in Python docs discussing the `` use of the SharedMemory class with NumPy arrays , accessing the same numpy.ndarray from two distinct Python shells '' .A major change that I 'd like to implement is manipulate array of class objects rather than integer values as I demonstrate b... | import numpy as npfrom multiprocessing import shared_memory # a simplistic class exampleclass A ( ) : def __init__ ( self , x ) : self.x = x # numpy array of class objects a = np.array ( [ A ( 1 ) , A ( 2 ) , A ( 3 ) ] ) # create a shared memory instanceshm = shared_memory.SharedMemory ( create=True , size=a.nbytes , n... | Sharing array of objects with Python multiprocessing |
Python | A friend of mine showed me the following Python code : Which returns True iff all the items in a are identical.I argued the code is hard to understand from first sight , and moreover - it is inefficient in memory usage , because two copies of a will be created for the comparison.I 've used Python 's dis to see what hap... | a [ 1 : ] == a [ : -1 ] > > > def stanga_compare ( a ) : ... return a [ 1 : ] ==a [ : -1 ] ... > > > a=range ( 10 ) > > > stanga_compare ( a ) False > > > a= [ 0 for i in range ( 10 ) ] > > > stanga_compare ( a ) True > > > dis.dis ( stanga_compare ) 2 0 LOAD_FAST 0 ( a ) 3 LOAD_CONST 1 ( 1 ) 6 SLICE+1 7 LOAD_FAST 0 ( ... | Does Slicing ` a ` ( e.g . ` a [ 1 : ] == a [ : -1 ] ` ) create copies of the ` a ` ? |
Python | I have a list of tuples that is created with the zip function . zip is bringing together four lists : narrative , subject , activity , and filer , each of which is just a list of 0s and 1s . Let 's say those four lists look like this : Now , I 'm ziping them together to get a list of boolean values indicating if any of... | narrative = [ 0 , 0 , 0 , 0 ] subject = [ 1 , 1 , 0 , 1 ] activity = [ 0 , 0 , 0 , 1 ] filer = [ 0 , 1 , 1 , 0 ] variables = ( `` narrative '' , `` subject '' , `` activity '' , `` filer '' ) reason = [ `` , `` .join ( [ some code to filter a tuple ] ) for x in zip ( narrative , subject , activity , filer ) ] reason # ... | Filter a tuple with another tuple in Python |
Python | I am using for loop in python to display old value and sum of new value . Following is my code.and the output of this loop is showing 48But i want to show output like Please let me know what i need to change in my code to display output like this . | numbers = [ 6 , 5 , 3 , 8 , 4 , 2 , 5 , 4 , 11 ] sum = 0for val in numbers : sum = sum+valprint ( sum ) 66+5 = 1111+3 = 1414+8 = 2222+4 = 2626+2 = 2828+5 = 3333+4 = 3737+11 = 48 | For loop to print old value and sum of old value |
Python | g = [ ( 'Books ' , '10.000 ' ) , ( 'Pen ' , '10 ' ) , ( 'test ' , ' a ' ) ] Here '10.000 ' and '10 ' are stringsHow to convert to below format , string to floatExpected outHere 10.000 and 10 are floats and a has to be stringI got error AttributeError : 'tuple ' object has no attribute 'isalpha ' | [ ( 'Books ' , 10.000 ) , ( 'Pen ' , 10 ) , ( 'test ' , ' a ' ) ] newresult = [ ] for x in result : if x.isalpha ( ) : newresult.append ( x ) elif x.isdigit ( ) : newresult.append ( int ( x ) ) else : newresult.append ( float ( x ) ) print ( newresult ) | How to convert data type for list of tuples string to float |
Python | I have a section of code that I need to get the output from : Though if it takes too long to get the output from get_gps_data ( ) , I would like to cancel the process and set gps to None . Modifying the function is impossible , so is there a way to specify the max amount of time to wait for some code to run and abort i... | gps = get_gps_data ( ) | Is it possible to specify the max amount of time to wait for code to run with Python ? |
Python | I have this piece of code : And I want to do something with it , which will empty them . Without losing their type.Something like this : Any hint ? | a = `` aa '' b = 1c = { `` b '' :2 } d = [ 3 , '' c '' ] e = ( 4,5 ) letters = [ a , b , c , d , e ] > > EmptyVars ( letters ) [ `` ,0 , { } , [ ] , ( ) ] | Empty a variable without destroying it |
Python | I have code like this : When this code is run with standard Python 2.7 interpreter , the file contains four lines as expected . However , when I run this code under PyPy , the file contains only two lines.Could someone explain the differences between Python and PyPy in working with files in append mode ? UPDATED : The ... | f1 = open ( 'file1 ' , ' a ' ) f2 = open ( 'file1 ' , ' a ' ) f1.write ( 'Test line 1\n ' ) f2.write ( 'Test line 2\n ' ) f1.write ( 'Test line 3\n ' ) f2.write ( 'Test line 4\n ' ) | PyPy file append mode |
Python | Simple dictionary : ( the sets may be turned into lists if it matters ) How do I convert it into a long/tidy DataFrame in which each column is a variable and every observation is a row , i.e . : The following works , but it 's a bit cumbersome : Is there any pandas magic to do this ? Something like : where unnest obvio... | d = { ' a ' : set ( [ 1,2,3 ] ) , ' b ' : set ( [ 3 , 4 ] ) } letter value0 a 11 a 22 a 33 b 34 b 4 id = 0tidy_d = { } for l , vs in d.items ( ) : for v in vs : tidy_d [ id ] = { 'letter ' : l , 'value ' : v } id += 1pd.DataFrame.from_dict ( tidy_d , orient = 'index ' ) pd.DataFrame ( [ d ] ) .T.reset_index ( level=0 )... | pandas : create a long/tidy DataFrame from dictionary when values are sets or lists of variable length |
Python | How do I loop through my 2 lists so that I can useto get OR useto get ( 1st element from 1st list , last element from 2nd list ) ( 2nd element from 1st list , 2nd to last element from 2nd list ) | a= [ 1,2,3,8,12 ] b= [ 2,6,4,5,6 ] [ 1,6,2,5,3,8,6,12,2 ] d= [ a , b , c , d ] e= [ w , x , y , z ] [ a , z , b , y , c , x , d , w ] | Create new list by taking first item from first list , and last item from second list |
Python | this is from the source code of csv2rec in matplotlibhow can this function work , if its only parameters are 'func , default ' ? ismissing takes a name and a value and determines if the row should be masked in a numpy array.func will either be str , int , float , or dateparser ... it converts data . Maybe not important... | def with_default_value ( func , default ) : def newfunc ( name , val ) : if ismissing ( name , val ) : return default else : return func ( val ) return newfunc | How can this python function code work ? |
Python | I was trying to improve the performance of the func function and I found that a simple change in how the aX list is generated improves the performance quite a bit : In Python 2.7.13 this results in : In Python 3.5.2 the difference is even larger : I need to process an ordered list integers ( i.e : a1 or a3 ) , so my qu... | import timeitimport numpy as npdef func ( a , b ) : return [ _ for _ in a if _ not in b ] Na , Nb = 10000 , 5000b = list ( np.random.randint ( 1000 , size=Nb ) ) # Ordered list of Na integersa1 = [ _ for _ in range ( Na ) ] # Random list of Na integersa2 = list ( np.random.randint ( Na , size=Na ) ) # Ordered list of N... | Why is processing a random list so much faster than processing an ordered list ? |
Python | I 'm working on a project that almost everywhere arguments are passed by key . There are functions with positional params only , with keyword ( default value ) params or mix of both . For example the following function : This function in the current code would be called like this : For me there is no point to name argu... | def complete_task ( activity_task , message=None , data=None ) : pass complete_task ( activity_task=activity_task , message= '' My massage '' , data=task_data ) complete_task ( activity_task , `` My message '' , task_data ) complete_task ( activity_task , message= '' success '' , task_data=json_dump ) | What is the pythonic way to pass arguments to functions ? |
Python | I have a list of dictionaries in python . Now how do i merge these dictionaries into single entity in python.Example dictionary isoutput shouled be : | input_dictionary = [ { `` name '' : '' kishore '' , `` playing '' : [ `` cricket '' , '' basket ball '' ] } , { `` name '' : '' kishore '' , `` playing '' : [ `` volley ball '' , '' cricket '' ] } , { `` name '' : '' kishore '' , `` playing '' : [ `` cricket '' , '' hockey '' ] } , { `` name '' : '' kishore '' , `` pla... | Merging list of dictionary in python |
Python | Aside from the obvious , I thought I 'd try this , just in case : Alas , Python 's response was quite hostile : As luck would have it , that 's a problem for me . See , I was thinking that maybe it would be a fun base type to play with , if I gave it a chance . Imagine my surprise ! ..and dismay . Is there no way to ge... | def somegen ( input=None ) : ... yield ... gentype = type ( somegen ( ) ) class subgen ( gentype ) : def best_function_ever ( ) : ... `` TypeError : Type generator is not an acceptable base type '' | Is there a way to subclass a generator in Python 3 ? |
Python | This is what they have : This is what I have : The first returns the correct sequence when employed , whereas mine proceeds 0 , 1 , 2 , 4 , 8 , 16 , 32 ... I am currently learning programming ( no prior computer science education ) , and it 's clear that the problem is how I 've defined my variables . What is the diffe... | def fib ( n ) : a , b = 0 , 1 while a < n : print a , a , b = b , a+b def fib ( n ) : a = 0 b = 1 while a < n : print a a = b b = b+a | Regarding the Fibonacci Sequence example in Python 's function tutorial |
Python | I have a list of names , and I would like my program to randomly select one of those names . I tried using the following : I also tried making each of the numbers as strings , using the eval ( ) function for randrange ( ) , but none of this worked . | import randomdef main ( ) : Arkansas = 1 Manchuria = 2 Bengal = `` 3 '' Baja_California = 4 Tibet = 5 Indonesia = 6 Cascade_Range = 7 Hudson_Bay = 8 High_Plains = 9 map = random.randrange ( 1 , 10 ) print ( map ) main ( ) | Print a variable selected by a random number |
Python | What is the reason for this discrepancy in behaviour ? | > > > x = 'foo ' > > > { 0 : locals ( ) .get ( ' x ' ) } { 0 : 'foo ' } > > > { 0 : locals ( ) .get ( ' x ' + spam ) for spam in [ `` ] } { 0 : None } | Python scoping in dict comprehension |
Python | I have a problem with the variations and the quantity related to it in the order summary page.It was working perfectly and all of a sudden ( this is an example to simplify ) : when I add to the cart 2 items : Item X with a size smallItem X with a size mediumWhen I change the quantity of item X size medium , this change... | { % block content % } < main > < div class= '' container '' > < div class= '' table-responsive text-nowrap '' style= '' margin-top:90px '' > < h2 > Order Summary < /h2 > < table class= '' table '' > < thead > < tr > < th scope= '' col '' > # < /th > < th scope= '' col '' > Item Title < /th > < th scope= '' col '' > Pri... | Changing in the Quantity of variants reflecting in the wrong item in Order Summary |
Python | Normally the dtype is hidden when it 's equivalent to the native type : But somehow that does n't apply to floor division or modulo : Why is there a difference ? Python 3.5.4 , NumPy 1.13.1 , Windows 64bit | > > > import numpy as np > > > np.arange ( 5 ) array ( [ 0 , 1 , 2 , 3 , 4 ] ) > > > np.arange ( 5 ) .dtypedtype ( 'int32 ' ) > > > np.arange ( 5 ) + 3array ( [ 3 , 4 , 5 , 6 , 7 ] ) > > > np.arange ( 5 ) // 3array ( [ 0 , 0 , 0 , 1 , 1 ] , dtype=int32 ) > > > np.arange ( 5 ) % 3array ( [ 0 , 1 , 2 , 0 , 1 ] , dtype=in... | Why is the dtype shown ( even if it 's the native one ) when using floor division with NumPy ? |
Python | I have been comparing the relative efficiency of numpy versus Python list comprehensions in multiplying together arrays of random numbers . ( Python 3.4/Spyder , Windows and Ubuntu ) .As one would expect , for all but the smallest arrays , numpy rapidly outperforms an list comprehension , and for increasing array lengt... | Numpy and Python list performance comparison Array Length Windows Ubuntu 1 0.2 0.4 2 2.0 0.6 5 1.0 0.5 10 3.0 1.0 20 0.3 0.8 50 3.5 1.9 100 3.5 1.9 200 10.0 3.0 500 4.6 6.0 1,000 13.6 6.9 2,000 9.2 8.2 5,000 14.6 10.4 10,000 12.1 11.1 20,000 12.9 11.6 50,000 13.4 11.4 100,000 13.4 12.0 200,000 12.8 12.4 500,000 13.0 12... | Why does the efficiency of numpy not scale |
Python | I saw the question Why does Process.fork make stuff slower in Ruby on OS X ? and was able to determine that Process.fork does not actually make tasks , in general , slower . However , it does seem to make Time.utc , in particular , much slower.Here are some results : One clue might be that the above takes place on OS X... | require 'benchmark'def do_stuff 50000.times { Time.utc ( 2016 ) } endputs `` main : # { Benchmark.measure { do_stuff } } '' Process.fork do puts `` fork : # { Benchmark.measure { do_stuff } } '' end main : 0.100000 0.000000 0.100000 ( 0.103762 ) fork : 0.530000 3.210000 3.740000 ( 3.765203 ) main : 0.100000 0.000000 0.... | Why is Time.utc slower in a forked process in Ruby on OS X ( and not in Python ) ? |
Python | I 'm currently working on an existing Django project which runs rather slowly ( I assume it 's mostly due to the AJAX calls ) . However , in order to prioritize optimization , I 'd like to know what the numbers behind the HTTP Response codes mean.Since the ones that take longer have larger numbers , I assume it 's how ... | [ 03/Dec/2011 22:25:00 ] `` GET /userbase HTTP/1.1 '' 200 5914 < -- This number [ 03/Dec/2011 22:25:39 ] `` GET /cohorts ? weekly=true HTTP/1.1 '' 200 27985 < -- This too [ 03/Dec/2011 22:26:13 ] `` GET /cohorts ? weekly=false HTTP/1.1 '' 200 11416 < -- and this one | Numbers following Django 's HTTP Response Code |
Python | I am trying to optimize my python code . One of the bottlenecks comes whenI tried to apply a function to a numpy array according to each element value . For instance , I have an array with thousand elements and I apply a function for values greater than a tolerance and another function ( Taylor series ) for the rest . ... | EPSILONZETA = 1.0e-6ZETA1_12 = 1.0/12.0ZETA1_720 = 1.0/720.0def masked_condition_zero ( array , tolerance ) : `` '' '' Return the indices where values are lesser ( and greater ) than tolerance `` '' '' # search indices where array values < tolerance indzeros_ = np.where ( np.abs ( array ) < tolerance ) [ 0 ] # create m... | Efficient way to do math in elements of a numpy array according to condition |
Python | I 'm trying to figure out what is the reason for having None as the default value for dict.get but no default value ( without specifying the default value ) for dict.popI was thinking that the reason for not having implicit default value for dict.pop is because you may have keys with value None so , in order to not get... | { } .get ( 'my_key ' ) # output : None { } .pop ( 'my_key ' ) # output : KeyError : 'my_key ' { 'my_key ' : None } .get ( 'my_key ' ) # output : None # but does n't tell you if the key is truly in the dictionary or not | dict.pop versus dict.get on the default return value |
Python | I am parsing a large ( 12 GB ) XML file made of about 135k more or less similar records ( this is an nmap dump ) . I noticed that the parsing speed is inconsistent , the time to parse similar records changes wildly . The following scaled-down code outputs the time needed to parse each 1 % of the records : This gives : ... | from xml.etree.ElementTree import iterparseimport timenrhosts = 0previous = time.time ( ) context = iterparse ( `` test.xml '' , events= ( `` start '' , `` end '' ) ) context = iter ( context ) event , root = context.next ( ) for event , elem in context : if event == 'end ' and elem.tag == `` host '' : root.clear ( ) #... | why is python XML parsing speed inconsistent ? |
Python | I have a sequence of JPG images . Each of the scans is already cropped to the exact size of one page . They are sequential pages of a valuable and out of print book . The publishing application requires that these pages be submitted as a single PDF file . I could take each of these images and just past them into a word... | sal @ bobnit : /media/NIKON D200/DCIM/100HPAIO/bat $ convert '*.jpg ' bat.pdfconvert : unable to open image ` *.jpg ' : No such file or directory @ blob.c/OpenBlob/2439.convert : missing an image filename ` bat.pdf ' @ convert.c/ConvertImageCommand/2775 . | Is there a programmatic way to transform a sequence of image files into a PDF ? |
Python | Suppose I have a simple Test class which inherits from numpy.ndarray ( documentation on ndarray subclassing ) . This class creates an object which is a partial view of another ndarray . Now I would like to create a method that modifies this view in-place . Something like : I would expect the method .change_view ( x ) t... | import numpyclass Test ( numpy.ndarray ) : def __new__ ( cls , info='Test class ' ) : base = numpy.ndarray.__new__ ( cls , ( 6 , 2 ) , dtype=float ) view = base [ 0:2 , : ] view.info = info return view def __array_finalize__ ( self , obj ) : if obj is None : return self.info = getattr ( obj , 'info ' , None ) def chang... | Changing subclassed ` ndarray ` view in-place |
Python | The doctest above passes on python 3 but fails on 2.x like this : This is just an example , I have seen this in several other situations ( e.g . whether a unicode string has an u prefix or not ) . I was wondering if there is an option for doctest to ignore trivial differences between python 2 and 3 like this ? I am not... | def fib_r ( n , memo= { 0 : 0 , 1 : 1 } ) : `` '' '' recursive fibonacci numbers generation with memoisation > > > [ fib_r ( n ) for n in range ( 10 ) ] [ 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 ] > > > fib_r ( 100 ) 354224848179261915075 '' '' '' if n not in memo : memo [ n ] = fib ( n - 1 ) + fib ( n - 2 ) return me... | Are portable doctests for python 2 / python 3 possible ? |
Python | I 'd like to compare every entry in array b with its respective column to find how many entries ( from that column ) are larger than the reference . My code seems embarrassingly slow and I suspect it is due to for loops rather than vector operations.Can we 'vectorize ' the following code ? After some more thought , I t... | import numpy as npn = 1000m = 200b = np.random.rand ( n , m ) p = np.zeros ( ( n , m ) ) for i in range ( 0 , n ) : # rows for j in range ( 0 , m ) : # cols r = b [ i , j ] p [ i , j ] = ( ( b [ : ,j ] > r ) .sum ( ) ) / ( n ) | Vectorized pythonic way to get count of elements greater than current element |
Python | I have a small question about static variable and TypeObjects.I use the API C to wrap a c++ object ( let 's call it Acpp ) that has a static variable called x.Let 's call my TypeObject A_Object : The TypeObject is attached to my python module `` myMod '' as `` A '' . I have defined getter and setters ( tp_getset ) so t... | typedef struct { PyObject_HEAD Acpp* a ; } A_Object ; > > > import myMod > > > myA1 = myMod.A ( some args ... ) > > > myA1.x = 34 # using the setter to set the static variable of Acpp > > > myA2 = myMod.A ( some other args ... ) > > > print myA2.x34 > > > # Ok it works ! > > > import myMod > > > myMod.A.x = 34 # what I... | Python API C++ : `` Static variable '' for a Type Object |
Python | So let 's say I defined the following function with type annotations : Is there a way to show the annotated types of this function ? Maybe a function types_of or something similar ? So that it can be used like this : | from typing import Listdef my_function ( input_1 : str , input_2 : int ) - > List [ int ] : pass > > types_of ( my_function ) [ str , int ] - > [ List [ int ] ] | How to print the type annotations of a function in Python ? |
Python | Pretty self-explanatory ( I 'm on Windows ) : Why does calling int once give me a long , whereas calling it twice gives me an int ? Is this a bug or a feature ? | > > > import sys , numpy > > > a = numpy.int_ ( sys.maxint ) > > > int ( a ) .__class__ < type 'long ' > > > > int ( int ( a ) ) .__class__ < type 'int ' > | Why does int ( maxint ) give a long , but int ( int ( maxint ) ) give an int ? Is this a NumPy bug ? |
Python | I 'm working with PyCrypto , and I seem to be successfully decrypting my data . However , the string I receive seems to behave strangely : The plaintext has the string I expect ( `` POEorOPE '' ) , but the output seems odd : Why does the string in the third print statement seem to take up zero space , and therefore hav... | ... plaintext = cipher.decrypt ( encrypted ) print 'plaintext length is % u ' % len ( plaintext ) print 'plaintext : % s ' % plaintextprint 'plaintext is `` % s '' ' % plaintext plaintext length is 16plaintext : POEorOPEplaintext is `` '' OEorOPE print repr ( plaintext ) 'POEorOPE\x08\x08\x08\x08\x08\x08\x08\x08 ' | Why is my python format % s taking no space ? |
Python | I get this code from leetcode.This code is used to implement poe ( x , n ) , which means x**n in Python.I want to know why it can implement pow ( x , n ) .It looks does n't make sense ... I understand But the core code : is really hard to understand.BTW , this code only works on Python 2.7 . If you want to test on Pyth... | class Solution ( object ) : def myPow ( self , x , n ) : if n == 0 : return 1 if n == -1 : return 1 / x return self.myPow ( x * x , n / 2 ) * ( [ 1 , x ] [ n % 2 ] ) if n == 0 : andif n == -1 : self.myPow ( x * x , n / 2 ) * ( [ 1 , x ] [ n % 2 ] ) myPow ( x*x , n / 2 ) * ( [ 1 , x ] [ n % 2 ] ) myPow ( x*x , n // 2 ) ... | Can someone explain this recursive for me ? |
Python | Why does range allow a non-default parameter ( stop ) to follow a default parameter ( start ) ? Case in point : Trying to emulate the signature is an obvious violation : I understand that the fact it is implemented in C probably allows for behavior that would be a violation in Pythonland . I 'm guessing this was done t... | > > > r = range ( 1 , 2 , 3 ) > > > print ( r.start , r.stop , r.step ) 1 2 3 > > > r = range ( 10 ) > > > print ( r.start , r.stop , r.step ) 0 10 1 def my_range ( start=0 , stop , end=1 ) : pass | range non-default parameter follows default one |
Python | I need to retrieve the list of attributes of a Python module.The catch , and this is where this question differs e.g . from this one , is that I want the list ordered according to the order they appear in the module.As an example , consider the moduleI want the list [ 'b1 ' , 'a0 ' , 'a1 ' ] .What I 've tried : Is ther... | # a_module.pyb1 = 1a0 = 1a1 = 2 > > > import a_module > > > dir ( a ) [ ... , 'a0 ' , 'a1 ' , 'b1 ' ] > > > from inspect import getmembers > > > [ x [ 0 ] for x in getmembers ( a_module ) ] [ ... , 'a0 ' , 'a1 ' , 'b1 ' ] | Get ordered list of attributes of a Python module |
Python | Consider this code : I know I could construct a conditional expression to do it : However , I do n't like testing if a boolean is true or false when I 'd rather just return the boolean . How would I just return its truthiness ? | test_string = 'not empty'if test_string : return Trueelse : return False return True if test_string else False | Returning the truthiness of a variable rather than its value ? |
Python | I have subclassed the dict and need to detect all its modifications . ( I know I can not detect an in-place modification of a stored value . That 's OK. ) My code : The problem is it works only for a straightforward assignment or deletion . It does not detect changes made by pop ( ) , popitem ( ) , clear ( ) and update... | def __setitem__ ( self , key , value ) : super ( ) .__setitem__ ( key , value ) self.modified = Truedef __delitem__ ( self , key ) : super ( ) .__delitem__ ( key ) self.modified = True | How to detect dict modification ? |
Python | I get an error in a production system , which I fail to reproduce in a development environment : Exception : I already tried to but a lot of strange characters into the variable data.But up to now I was not able to reproduce an UnicodeEncodeError.What needs to be in data to get an UnicodeEncodeError ? UpdateUpdate2If I... | with io.open ( file_name , 'wt ' ) as fd : fd.write ( data ) File `` /home/ ... /foo.py '' , line 18 , in foo fd.write ( data ) UnicodeEncodeError : 'ascii ' codec ca n't encode character u'\xe4 ' in position 6400 : ordinal not in range ( 128 ) python -c 'import locale ; print locale.getpreferredencoding ( ) 'UTF-8 | How to reproduce UnicodeEncodeError ? |
Python | I have a DataFrame , df , in pandas with series df.A and df.B and am trying to create a third series , df.C that is dependent on A and B as well as the previous result . That is : C [ 0 ] =A [ 0 ] C [ n ] =A [ n ] + B [ n ] *C [ n-1 ] what is the most efficient way of doing this ? Ideally , I would n't have to fall bac... | import pandas as pda = [ 2 , 3 , -8 , -2 , 1 ] b = [ 1 , 1 , 4 , 2 , 1 ] c = [ 2 , 5,12,22,23 ] df = pd.DataFrame ( { ' A ' : a , ' B ' : b , ' C ' : c } ) df | Recurrence relation in Pandas |
Python | I have numpy array and I want to use power series like taylor series of e^x , and I am wondering how to implement this in python . For the simplicity purpose , I think I can use maclaurin series at x0=0 , wheres x is numpy array . Basically , I have 1 dim pixel vector , and I want to non-linearly expand each pixel valu... | import numpy as nparr= np.array ( [ [ 120.0,24.0,12.0 ] , [ 14.0,28.0,43.0 ] ] ) arr= arr/255.0def maclurin_exp ( x , power ) : res = x*0 for i in range ( power ) : res += x**i/math.factorial ( i ) return res # # test my code : maclurin_exp ( x=arr , power=3 ) pixel = [ 1,2,3,4,5,6,7,8 ] | implementation of using Maclaurin series of e^x in python |
Python | I am trying Google 's Native Client SDK.OS is Windows 7 , I 've already installed python 2.7.9 and setup the environment variable path accordingly.I also downloaded nacl_sdk.zip from https : //developer.chrome.com/native-client/sdk/download and extracted it.However , as I run the command `` naclsdk list '' as it is des... | C : \Temp\nacl_sdk > naclsdk list Traceback ( most recent call last ) : File `` C : \Temp\nacl_sdk\sdk_tools\sdk_update_main.py '' , line 759 , in sys.exit ( main ( sys.argv [ 1 : ] ) ) File `` C : \Temp\nacl_sdk\sdk_tools\sdk_update_main.py '' , line 752 , in main InvokeCommand ( args ) File `` C : \Temp\nacl_sdk\sdk_... | Can not use Google Native Client SDK on Windows 7 |
Python | I would like to convert two arrays ( x and y ) into a frequency n x n matrix ( n = 5 ) , indicating each cell the number of point that contains . It consists on resampling both variables into five intervals and count the existing number of points per cell.I have tried using pandas pivot_table but do n't know the way of... | import pandas as pdimport numpy as npimport matplotlib.pyplot as plt # Arrays example . They are always float type and ranging 0-100 . ( n_size array = 15 ) x = 100 * np.random.random ( 15 ) y = 100 * np.random.random ( 15 ) # Df created for trying to pivot and counting values per celldf = pd.DataFrame ( { ' X ' : x , ... | Convert X and Y arrays into a frequencies grid |
Python | My code call numerous `` difference functions '' to compute the `` Yin algorithm '' ( fundamental frequency extractor ) .The difference function ( eq . 6 in the paper ) is defined as : And this is my implementation of the difference function : For instance with : Is there a way to optimize this double-loop computation ... | def differenceFunction ( x , W , tau_max ) : df = [ 0 ] * tau_max for tau in range ( 1 , tau_max ) : for j in range ( 0 , W - tau ) : tmp = long ( x [ j ] - x [ j + tau ] ) df [ tau ] += tmp * tmp return df x = np.random.randint ( 0 , high=32000 , size=2048 , dtype='int16 ' ) W = 2048tau_max = 106differenceFunction ( x... | Optimize computation of the `` difference function '' |
Python | Simple question as i just want to write more pythonic code . I want to convert the following into a list comprehensionWhat i do n't understand is how to walk through the counts list . I do n't want a nested for like : The code i have now is working but I 'd like to understand python better and use the language as it sh... | index_row = 0for row in stake_year.iterrows ( ) : self.assertTrue ( row [ 0 ] == counts [ index_row ] [ 0 ] ) self.assertTrue ( row [ 1 ] [ 0 ] == counts [ index_row ] [ 1 ] ) index_row += 1 [ self.assertTrue ( x [ 0 ] == counts [ y ] [ 0 ] for x in stake_year for y in counts ] | list comprehension with concurrent loops python |
Python | I have a piece of code ( an xls parser ) that does some validation on the fields and returns with yield a generator that contains every row of the xls.Now , i have to collect validation errors in a list , and use them when the generator is exhausted.This is a piece of code that represent the parser and a poor designed ... | error_list = [ ] def gen ( limit ) : # xls parser for x in range ( limit ) : if x % 2 : # fake error contition error_list.append ( x ) else : yield ( x*x ) # return def gen ( limit ) : # xls parser error_list = [ ] results = [ ] for x in range ( limit ) : if x % 2 : # fake error contition error_list.append ( x ) else :... | Using Yield and return a list of error |
Python | I am writing a console app with the Click library ( almost no experience with it yet ) and Python 3.6.I need a program that can be called like this from the OS shell : to iterate through the list of all the files in the current directory ( or whatever the mask specifies ) and do something with them.How can this be achi... | myapp -- myoptiona=123 -- myoptionb=456 * | How to iterate through the list of files supplied by the shell in a Python 3 Click app ? |
Python | I 'll preface this with the statement that I would n't do this in the first place and that I ran across this helping a friend.Consider the data frame dfThis is a data frame of objects where the objects are lists . In my friend 's code , they had : Which breaks as I had hopedHowever , if those values were numpy arrays i... | df = pd.DataFrame ( pd.Series ( [ [ 1.2 ] ] ) ) df 00 [ 1.2 ] df.astype ( float ) ValueError : setting an array element with a sequence . df = pd.DataFrame ( pd.Series ( [ np.array ( [ 1.2 ] ) ] ) ) df 00 [ 1.2 ] df.astype ( float ) 00 1.2 df = pd.DataFrame ( pd.Series ( [ np.array ( [ 1.2 , 1.3 ] ) ] ) ) df 00 [ 1.2 ,... | DataFrame of objects ` astype ( float ) ` behaviour different depending if lists or arrays |
Python | I am using a permutation test ( pulling random sub-samples ) to test the difference between 2 experiments . Each experiment was carried out 100 times ( =100 replicas of each ) . Each replica consists of 801 measurement points over time . Now I would like to perform a kind of permutation ( or boot strapping ) in order t... | import matplotlib.pyplot as pltimport numpy as npfrom multiprocessing import current_process , cpu_count , Process , Queueimport matplotlib.pylab as pldef groupDiffsInParallel ( queue , d1 , d2 , nrOfReplicas , nrOfPermuts , timesOfInterestFramesIter ) : allResults = np.zeros ( [ nrOfReplicas , nrOfPermuts ] ) # e.g . ... | Why is the curve of my permutation test analysis not smooth ? |
Python | I have dataframe in this shape : I would like to move every second row of that dataframe to the row above so that there are only combined rows left as seen in the expected result : Is it possible to do with Pandas ? | A B C D E 213-1 XL NaN NaN NaN 21 22.0 12 232.0 101.32 23-0 L NaN NaN NaN 12 23 12 232.2 NaN 31-0 LS NaN NaN NaN 70 70 23 NaN 21.22 ID Name A B C D E 213-1 XL 21 22.0 12 232.0 101.32 23-0 L 12 23 12 232.2 NaN 31-0 LS 70 70 23 NaN 21.22 | Move every second row to row above in pandas dataframe |
Python | I tried to use python practice if __name__ == `` __main__ '' : on shellscript.Sample scripts are the following : a.sh : b.sh : You can call it with bash a.sh.If you call bash a.sh , you 'll get like the following : Here is my question.How can I get file name itself without using $ 0 ? I do n't want to write file name d... | # ! /bin/bashfilename= '' a.sh '' function main ( ) { echo `` start from $ 0 '' echo `` a.sh is called '' source b.sh bfunc } [ [ `` $ 0 '' == `` $ { filename } '' ] ] & & main # ! /bin/bashfilename= '' b.sh '' function main ( ) { echo `` start from $ 0 '' echo `` b.sh is called '' } function bfunc ( ) { echo `` hello ... | How to get shellscript filename without $ 0 ? |
Python | I saw some code in the Whoosh documentation : I read that the with statement executes __ enter__ and __ exit__ methods and they are really useful in the forms `` with file_pointer : '' or `` with lock : '' . But no literature is ever enlightening . And the various examples shows inconsistency when translating between t... | with ix.searcher ( ) as searcher : query = QueryParser ( `` content '' , ix.schema ) .parse ( u '' ship '' ) results = searcher.search ( query ) | Confused about Python 's with statement |
Python | The empty production ruleis useful in lex-yacc LR bottom up parser generators ( e.g . PLY ) .In what context should one use Empty productions in PEG parsers e.g . pyparsing ? | nonterminal - > epsilon | What is the role of the Empty production for PEGs ? |
Python | I have simple table : I want to write Query using Django ORM to be similar to : I finally ended with : But I 'm receiving error : but when i write : I 'm receiving an error : | class Author ( models.Model ) : name = models.CharField ( max_length=40 ) SELECT DISTINCT LOWER ( name ) from my_app_author ; Author.objects.annotate ( name_lower=Func ( F ( 'name ' ) , function='lower ' ) ) .distinct ( 'name_lower ' ) Traceback ( most recent call last ) : File `` /opt/venv/lib/python3.4/site-packages/... | Django 1.8 selecting distinct on lower ( ) function throws AttributeError |
Python | Say I have a package with a console script such asIf I set and explicit build tag using egg_info -b mytag the resulting script has __requires__ = 'eg-package===0.0.1mytag ' , i.e . with 3 `` = '' signs . This occurs when the tag is not something conventional like b1 for a beta release.At first I thought this was a bug ... | from setuptools import setupsetup ( name='eg_package ' , version= ' 0.0.1 ' , description='Trivial test package ' , packages= [ 'eg_package ' , ] , entry_points= { 'console_scripts ' : [ 'foo = eg_package.main : main ' , ] } , ) | What is the purpose of setuptools requirements of the form `` package===version '' |
Python | I 've been playing around with Celery / Django . In their example celery.py file there is the following line Where lambda : settings.INSTALLED_APPS is the actual parameter for the formal parameter packages in autodiscover_tasks ( ) . And settings.INSTALLED_APPS is a tuple . autodiscover_tasks ( ) then either calls the ... | app.autodiscover_tasks ( lambda : settings.INSTALLED_APPS , force=True ) packages = packages ( ) if callable ( packages ) else packages | Lambda use case confusion |
Python | i 'm using CNN for image classification ; I do data augmentation with keras ImageDataGeneratorI think i 'm missing something.In situation A I use a batch size of 64 , I need 20 sec per epoch . Situation B with batch size of 15 i need 60sec per epoch . Situation C with batch size 256 need 345 seconde per epoch.What I un... | A /// train =model.fit_generator ( image_gen.flow ( train_X , train_label , batch_size=64 ) , epochs=100 , verbose=1 , validation_data= ( valid_X , valid_label ) , class_weight=class_weights , callbacks= [ metrics ] , steps_per_epoch=len ( train_X ) /64 ) # 1 epoch =20 secondesB /// train =model.fit_generator ( image_g... | Bigger batch size reduce training time |
Python | I have a dictionary of lists . Each list is a sequence of numbers . No two lists are equal but two or more lists may start with the same sequence of numbers ( see my example input below ) . What I want to do is find these common sequences and make them a new element in the dictionary.Sample input : Sample output : The ... | sequences = { 18 : [ 1 , 3 , 5 , 6 , 8 , 12 , 15 , 17 , 18 ] , 19 : [ 1 , 3 , 5 , 6 , 9 , 13 , 14 , 16 , 19 ] , 25 : [ 1 , 3 , 5 , 6 , 9 , 13 , 14 , 20 , 25 ] , 11 : [ 0 , 2 , 4 , 7 , 11 ] , 20 : [ 0 , 2 , 4 , 10 , 20 ] , 26 : [ 21 , 23 , 26 ] , } expected_output = { 6 : [ 1 , 3 , 5 , 6 ] , 18 : [ 8 , 12 , 15 , 17 , 18... | Finding common list sequences |
Python | In a Django admin site , I have this class.I want to save a previous version of a object ( Servers ) which is a manytomany field to find changes on the object.With normal CharField this work , but for manytomany fields I got this error : here is my objectclass | `` < SourceDestinationGroup : asdas > '' needs to have a value for field `` id '' before this many-to-many relationship can be used . class SourceDestinationGroup ( models.Model ) : STATE_CHOICES = ( ( ' C ' , 'in Change ' ) , ( ' F ' , 'Finished ' ) ) ServerGroupName = models.CharField ( max_length=256 ) Description =... | Django save previous object from models |
Python | Could someone explain why the following program fails : with the message : But if I simply change the variable x to an array , it works : with the outputThe reason I am confused is , if from f ( ) it ca n't access x , why it becomes accessible if x is an array ? Thanks . | def g ( f ) : for _ in range ( 10 ) : f ( ) def main ( ) : x = 10 def f ( ) : print x x = x + 1 g ( f ) if __name__ == '__main__ ' : main ( ) Traceback ( most recent call last ) : File `` a.py '' , line 13 , in < module > main ( ) File `` a.py '' , line 10 , in main g ( f ) File `` a.py '' , line 3 , in g f ( ) File ``... | Variable scope in nested functions |
Python | I have a script which takes a lot of time and ca n't finish so far after 2 days ... I parsed 1 file into 2 dictionaries as the following : . -- The aim is to find TE_id whose TEstart or TEend or both are located between gene_id ' gstart and gend in each chr ( key ) .The above should be changed to `` find TE_id whose ra... | gfftree = { 'chr1 ' : [ ( gene_id , gstart , gend ) , ... ] , 'chr2 ' : [ ( gene_id , gstart , gend ) , ... ] , ... } TElocation = { 'chr1 ' : [ ( TE_id , TEstart , TEend ) , ... ] , 'chr2 ' : [ ( TE_id , TEstart , TEend ) , ... ] , ... } TE_in_TSS = [ ] for TErange in TElocation [ chromosome ] : TE_id , TEstart , TEen... | Double loop takes time |
Python | I 'm attempting to upload a tarball and wheel for a new package to PyPI using twine which was recently installed under a conda environment ( Miniconda3 ) . After I enter my username I expect to be prompted for my password , but this never happens and everything just hangs . Any suggestions as to what is causing this un... | $ twine -- versiontwine version 1.11.0 ( pkginfo : 1.4.2 , requests : 2.19.1 , setuptools : 40.2.0 , requests-toolbelt : 0.8.0 , tqdm : 4.25.0 ) $ twine upload -- repository-url https : //test.pypi.org/legacy/ dist/*Uploading distributions to https : //test.pypi.org/legacy/Enter your username : my_user_name | Twine hangs without prompting for password |
Python | I am using RequestHandler for making Web Based call using Tornado Web framework . Previously I was using Tornado Version 5.1.1 which supported @ gen.coroutine and yield . I am moving my tornado version to 6.0.2 and recently as they have depreciated decorated coroutines So I am moving my code to native coroutines . But ... | import tornado.ioloop as ioloopimport tornado.web as webfrom RequestHandler import MainHandlerdef main ( ) : application = web.Application ( [ ( r '' / '' , MainHandler ) , ] ) application.listen ( 8080 ) ioloop.IOLoop.current ( ) .start ( ) if __name__ == '__main__ ' : main ( ) import tornado.webimport tornado.genclas... | Different behaviour for Yield and Await in case of RequestHandler write ( Tornado Web Framework ) |
Python | I am stuck in django and would really appreciate it if someone could help me.I need to have an entry point for a 3rd party API . So I created a view and decorated it with @ csrf_exemptNow the problem is I am not able to access any session variables I set before.edit - I set multiple session variables like user email to... | @ csrf_exemptdef ppConfirmPayment ( request ) : print ( request.session , `` ======================================= '' ) for key , value in request.session.items ( ) : print ( ' { } = > { } '.format ( key , value ) ) return ppConfirmPaymentProcess ( request ) | With Django @ csrf_exempt , request.session is always empty |
Python | I have this list of lists : Practically cont_det is a huge list with lots of sub-lists with irregular length of each sub-list . This is just a sample case for demonstration . I want to get the following output : The logic behind this is zip_longest the list of lists but in case there is any sub-list whose length is les... | cont_det = [ [ 'TASU 117000 0 ' , `` TGHU 759933 - 0 '' , 'CSQU3054383 ' , 'BMOU 126 780-0 ' , `` HALU 2014 13 3 '' ] , [ '40HS ' ] , [ 'Ha2ardous Materials ' , 'Arm5 Maehinery ' ] ] [ [ 'TASU 117000 0 ' , '40HS ' , 'Ha2ardous Materials ' ] , [ 'TGHU 759933 - 0 ' , '40HS ' , 'Arm5 Maehinery ' ] , [ 'CSQU3054383 ' , '40... | Itertools zip_longest with first item of each sub-list as padding values in stead of None by default |
Python | I have a function that , in the simplest of cases , operates on an iterable of items.Sometimes , I do not want to pass it an iterable of items directly , but rather an object that provides a method to get the iterable : I can merge these two cases like this : This works just fine . Now I get a third use case that looks... | def foo ( items ) : for item in items : # do stuff def foo ( obj ) : for item in obj.iteritems ( ) : # do same stuff as above def foo ( obj ) : try : items = obj.iteritems ( ) except ValueError : items = obj for item in items : # do stuff def foo ( objs ) : for item in itertools.chain.from_iterable ( obj.iteritems ( ) ... | Elegantly handle different parameter types |
Python | I have a namedtuple type defined inside a module consisting of two classes , foo and bar , defined in the module 's only file , mod.py . I am able to create instances of both foo and bar without issue and pickle them . I am now trying to Cythonize it so that I can distribute the module as bytecode . The module file str... | ./mod.pyx./setup.py./demo.py import collectionsfoo = collections.namedtuple ( 'foo ' , ' A B ' ) class bar : def __init__ ( self , A , B ) : self.A = A self.B = B from distutils.core import setupfrom distutils.extension import Extensionfrom Cython.Build import cythonizesetup ( ext_modules= cythonize ( [ Extension ( 'mo... | Pickling of a namedtuple instance succeeds normally , but fails when module is Cythonized |
Python | When I use : I get : How can I change my code to get : Thank you very much.obs : this is just a a simplified example . try to refrain from making recommendations about sql injection . | for i in Selection : Q = `` SELECT columnA FROM DB WHERE wbcode= ' '' +i+ '' ' and commodity= ' 1 ' '' cursor.execute ( Q ) ydata [ i ] = cursor.fetchall ( ) ydata = { 'GBR ' : [ ( u'695022 ' , ) , ( u'774291 ' , ) , ( u'791499 ' , ) ... ] } ydata = { 'GBR ' : [ 695022 , 774291 , 791499 , ... ] } | Simple sqlite question |
Python | How do I sum duplicate elements in a list of lists of dictionaries ? Sample list : Expected output : | data = [ [ { 'user ' : 1 , 'rating ' : 0 } , { 'user ' : 2 , 'rating ' : 10 } , { 'user ' : 1 , 'rating ' : 20 } , { 'user ' : 3 , 'rating ' : 10 } ] , [ { 'user ' : 4 , 'rating ' : 4 } , { 'user ' : 2 , 'rating ' : 80 } , { 'user ' : 1 , 'rating ' : 20 } , { 'user ' : 1 , 'rating ' : 10 } ] , ] op = [ [ { 'user ' : 1 ... | Sum values in a list of lists of dictionaries using common key-value pairs |
Python | Consider the following functionIf I use Sphinx to generate code from my docstring , it looks like this ( I 'm using the default theme haiku this time , without many changes in the rst or conf.py file ) : Are there any themes -or any other workarounds- that resolve the problems that I indicated with colors ? I tried dif... | # in mymodule.py : def myfunc ( num , mystring ) : `` '' '' replicates a string : param num : a positive integer : param mystring : a string : return : string concatenated with itself num times : Example : > > > num = 3 > > > mystring = `` lol '' > > > myfunc ( num , mystring ) `` lollollol '' `` '' '' return num*mystr... | More consistent Sphinx themes |
Python | While studying Pandas Style , I got to the following : How should I read is_max = s == s.max ( ) ? | def highlight_max ( s ) : `` ' highlight the maximum in a Series yellow. `` ' is_max = s == s.max ( ) return [ 'background-color : yellow ' if v else `` for v in is_max ] | is_max = s == s.max ( ) | How should I read this ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.