text stringlengths 46 37.3k | 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 a... | 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 correct... | 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... | 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 ? <code> np.mean ( data , axis=1 , dtyp... | 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 ide... | 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 i... | 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 ... | 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 inc... | 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.... | 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... | 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 ch... | 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 p... | 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.h... | 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 <code> import reinputlist = 'Project= '' Sparcy '' Desc= '' '' \nProject= '' Libs '' Desc= '' '... | 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 . <code> 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 inde... | 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 duc... | 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 ? <code> 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 ' ]... | 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... | 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 relat... | 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 : <code> 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 fl... | 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 ? <code> # Exam... | 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... | 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 follo... | 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 eac... | 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 ? <code> s = [ [ ' a ' , ' b ' , ' c ' , 'd ' ] , [ ' e ' , ' f ' , '... | 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 ? <code> l1 = [ { ' a ' : 1 , ' b ' : 2 , ' c ' : 3 , 'd ' : 4 } , { ' a ' : 5 , ' b ' : 6 , ' c ' : 7 , 'd ' : 8 } ] l2 = [ { ' a ' : 5 , ' ... | 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 demo... | 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... | 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 ... | 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 . <code> numbers = [ 6 , 5 , 3 , 8 , 4 , 2 , 5 , 4 , 11 ] sum = ... | 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 ' <code> [ ( 'Bo... | 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 an... | 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 ? <code> 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 ? UPDAT... | 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 unn... | 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 ) <code> 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 ,... | 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 ... | 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 ) ,... | 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 ... | 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 : <code> input_dictionary = [ { `` name '' : '' kishore '' , `` playing '' : [ `` cricket '' , '' basket ball '' ] } , { `` name '' : '' kishore '' , `` playing ''... | 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 ... | 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 ... | 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 . <code> import randomdef main ( ) : Arkansas = 1 Manchuria = 2... | Print a variable selected by a random number |
Python : What is the reason for this discrepancy in behaviour ? <code> > > > 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 , th... | 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 <code> > > > import numpy as np > > > np.arange ( 5 ) array ( [ 0 , 1 , 2 , 3 , 4 ] ) > > > np.arange ( 5... | 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 ar... | 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 plac... | 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 i... | 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 th... | 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 t... | 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... | 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 in... | 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_vie... | 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 ?... | 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 thou... | 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_gets... | 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 : <code> from typing import Listdef my_function ( input_1 : str , input_2 : 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 ? <code> > > > import sys , numpy > > > a = numpy.int_ ( sys.maxint ) > > > int ( a ) .__class__ < type 'long ' > > > > int ( int ( a ) ) .__class__ < t... | 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 ther... | 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 tes... | 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 w... | 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 ... | 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 ? <code> test_string = 'not empty'if test_string : return Trueelse : return False ret... | 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 ( ) a... | 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 ? UpdateUp... | 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... | 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 p... | 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 ... | 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 t... | 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 com... | 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... | 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 ... | 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 thi... | 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... | 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 ) i... | 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 ? <code> 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... | 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 fi... | 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 ... | 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 ? <code> 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 : <code> class Author ( models.Model ) : name = models.CharField ( max_length=40 ) SELECT DISTINCT LOWER ( name ) from my_app_author ; Aut... | 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 w... | 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 c... | 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.... | 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 outp... | 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 <code> `` < SourceDestinationGroup : asdas > '' ne... | 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 . <code> def g ( f ) : for _ in range ( 1... | 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... | 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 causin... | 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 coroutin... | 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... | 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 leng... | 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 t... | 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... | 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 . <code> for i in Selection : Q = `` SELECT columnA FROM DB WHERE wbcode= ' '' +i+ '' ' and commodity= ' 1 ' '' cursor.execute ( ... | Simple sqlite question |
Python : How do I sum duplicate elements in a list of lists of dictionaries ? Sample list : Expected output : <code> data = [ [ { 'user ' : 1 , 'rating ' : 0 } , { 'user ' : 2 , 'rating ' : 10 } , { 'user ' : 1 , 'rating ' : 20 } , { 'user ' : 3 , 'rating ' : 10 } ] , [ { 'user ' : 4 , 'rating ' : 4 } , { 'user ' : 2 ,... | 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 ... | More consistent Sphinx themes |
Python : While studying Pandas Style , I got to the following : How should I read is_max = s == s.max ( ) ? <code> 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.