lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I have a Django app which I want to be able to use in multiple instances . One model ( Listing ) can have a variable number of fields ( for the different instances ) but will then always have exactly those extra fields for the instance . I want these extra fields added through admin so I 've created models like this : ... | class BespokeField ( models.Model ) : name = models.CharField ( max_length = 20 , verbose_name = `` Field Title '' ) def __unicode__ ( self ) : return self.nameclass Listing ( models.Model ) : name = models.CharField ( verbose_name = 'Listing ' , max_length = 30 ) slug = models.SlugField ( verbose_name = `` Slug '' , a... | Display an unknown number of fields in Django template with field content of another record as the label |
Python | How to get full row of data for groupby relsult ? How the get the full row ? I tried filtering but df [ df.e == df.groupby ( ' a ' ) [ ' b ' ] .max ( ) ] but size is different : ( Original data : Groupby ( [ 1,7 ] ) [ 14 ] .max ( ) gives me the result but in grouped series as 1 and 7 as index I wanted the corresponding... | df a b c d e0 a 25 12 1 201 a 15 1 1 12 b 12 1 1 13 n 25 2 3 3In [ 4 ] : df = pd.read_clipboard ( ) In [ 5 ] : df.groupby ( ' a ' ) [ ' b ' ] .max ( ) Out [ 5 ] : aa 25b 12n 25Name : b , dtype : int64 a b c d ea 25 12 1 20b 12 1 1 1n 25 2 3 3 0 1 2 3 4 5 6 7 8 9 EVE00101 Trial DRY RUN PASS 1610071 1610071 Y 20140808 Na... | Groupby returning full row for max occurs |
Python | I 'm trying to add a few interactive things the to Django admin page via a simple RESTful api and Javascript . Should be simple , but I 'm facing a weird issue where every single one of my requests from javascript is returning a 403 authorization error . Note that this only applies to js . I can hit the url from a brow... | $ .ajax ( { xhrFields : { withCredentials : true } , type : 'PATCH ' , url : 'path/to/my/endpoint , data : { aParam : someValue , 'csrfmiddlewaretoken ' : getCookie ( 'csrftoken ' ) } , success : doSomething , error : doSomething } ) ; class MyObjectDetail ( RetrieveUpdateDestroyAPIView ) : queryset = MyObject.objects.... | Django Rest framework replacing my currently authenticated user with AnonymousUser whenever I call it via ajax ? |
Python | I am trying to filter data from a dataframe which are less than a certain value . If there is no NaN then its working fine . But when there is a nan then it is ignoring the NaN value . I want to include all the time its does n't matter its less than or bigger than the comparing value . In the above result 5,6,7,9 is sh... | import pandas as pdimport numpy as npdf = pd.DataFrame ( { 'index ' : [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] , 'value ' : [ 5 , 6 , 7 , np.nan , 9 , 3 , 11 , 34 , 78 ] } ) df_chunked = df [ ( df [ 'index ' ] > = 1 ) & ( df [ 'index ' ] < = 5 ) ] print ( 'df_chunked ' ) print ( df_chunked ) df_result = df_chunked [ ( df_... | Value filter in pandas dataframe keeping NaN |
Python | Suppose we have a string a = `` 01000111000011 '' with n=5 `` 1 '' s. The ith `` 1 '' , I would like to replace with the ith character in `` ORANGE '' .My result should look like : What could be the finest way to solve this problem in Python ? Is it possible to bind an index to each substitution ? Many thanks ! Helga | b = `` 0O000RAN0000GE '' | Python : Replace ith occurence of x with ith element in list |
Python | I 'm trying to wrap a little handy piece of C++ code that is intended to generate video+audio on windows using VFW , the C++ library lives here and the descriptions says : Uses Video for Windows ( so it 's not portable ) . Handy if you want to quickly record a video somewhere and do n't feel like wading through the VfW... | % module aviwriter % { # include `` aviwriter.h '' % } % typemap ( in ) ( const unsigned char* buffer ) ( char* buffer , Py_ssize_t length ) % { if ( PyBytes_AsStringAndSize ( $ input , & buffer , & length ) == -1 ) SWIG_fail ; $ 1 = ( unsigned char* ) buffer ; % } % typemap ( in ) ( const void* buffer ) ( char* buffer... | Bug writing audio using custom video writer library |
Python | I have a django 1.5 running on Google App Engine using the djangoappengine module for the stitching.Everything works fine , except that about a half of the calls to /_ah/queue/deferred raise the following import error : As you can see , the djangoappengine module sits inside the third_party directory , and this directo... | Traceback ( most recent call last ) : File `` ... ./third_party/djangoappengine/deferred/handler.py '' , line 2 , in < module > from djangoappengine import mainImportError : No module named djangoappengine sys.path.insert ( 0 , os.path.join ( os.path.dirname ( __file__ ) , 'third_party ' ) ) handlers : - url : /_ah/que... | /_ah/queue/deferred strange import error |
Python | I expected the terminate ( ) method to kill the two processes : Running the code gives : I was expecting : | import multiprocessingimport timedef foo ( ) : while True : time.sleep ( 1 ) def bar ( ) : while True : time.sleep ( 1 ) if __name__ == '__main__ ' : while True : p_foo = multiprocessing.Process ( target=foo , name='foo ' ) p_bar = multiprocessing.Process ( target=bar , name='bar ' ) p_foo.start ( ) p_bar.start ( ) tim... | Why are the children failing to die ? |
Python | I am trying to accept tuple and list as object types in an __add__ method in Python . Please see the following code : The error I get when running it in the Python interpreter is : I simply can not figure our why this is n't working . This is homework for a college course and I have very little experience with Python .... | class Point ( object ) : ' '' A point on a grid at location x , y '' ' def __init__ ( self , x , y ) : self.X = x self.Y = y def __str__ ( self ) : return `` X= '' + str ( self.X ) + `` Y= '' + str ( self.Y ) def __add__ ( self , other ) : if not isinstance ( other , ( Point , list , tuple ) ) : raise TypeError ( `` Mu... | Implementing Tuples and Lists in the isinstance Function in Python 2.7 |
Python | this is my code : mypy throw error : Argument 1 of `` __eq__ '' incompatible with supertype `` object '' . But if I remove __eq__ method , mypy wo n't complain it though compare is same as __eq__ , what should I do ? | class Person : def __init__ ( self , id ) : self.id = id def __eq__ ( self , other : 'Person ' ) - > bool : return self.id == other.id def compare ( self , other : 'Person ' ) - > bool : return self.id == other.id | mypy : `` __eq__ '' incompatible with supertype `` object '' |
Python | I 'm writing a Python parser to learn Flex and Bison , and I 'm trying to find out why only the first of these programs is valid Python.a.py : produces no error.b.py : produces this error : and c.py : produces this error : I 'm using Python 2.6.5 ( r265:79063 , Apr 16 2010 , 13:09:56 ) [ GCC 4.4.3 ] on linux2 ( Ubuntu ... | \ # This is valid Python \ # This is not valid Python File `` b.py '' , line 1 \ ^IndentationError : unexpected indent if True : pass \ # This is not valid Python File `` c.py '' , line 4 # This is not valid Python ^SyntaxError : invalid syntax | Why do indented explicit line continuations not allow comments in Python ? |
Python | Using this small reproducible example , I 've so far been unable to generate a new integer array from 3 arrays that contains unique groupings across all three input arrays . The arrays are related to topographic properties : The idea is that the geographic contours are broken into 3 different properties using GIS routi... | import numpy as npasp = np.array ( [ 8,1,1,2,7,8,2,3,7,6,4,3,6,5,5,4 ] ) .reshape ( ( 4,4 ) ) # aspectslp = np.array ( [ 9,10,10,9,9,12,12,9,10,11,11,9,9,9,9,9 ] ) .reshape ( ( 4,4 ) ) # slopeelv = np.array ( [ 13,14,14,13,14,15,16,14,14,15,16,14,13,14,14,13 ] ) .reshape ( ( 4,4 ) ) # elevation | Intersect multiple 2D np arrays for determining zones |
Python | Situation ( Note : The following situation is just exemplary . This question applys to anything that can evaluate to bool ) A default list should be used if the user does not provide a custom list : You can shorten this to : Now , as per https : //docs.python.org/2.7/reference/expressions.html # or ... The expression x... | default_list = ... custom_list = ... if custom_list : list = custom_listelse : list = default_list default_list = ... custom_list = ... list = custom_list if custom_list else default_list list = custom_list or default_list | Is 'or ' used on the right-hand-side of an assignment pythonic ? |
Python | I have dataframe like this : i 'm trying to aggregate it like this : and it works but i also need to add grouped logins to row , to make row like this : I tried something like lambda x : x.ait [ 0 , 1 ] but it doesnt work | x = pd.DataFrame ( { 'audio ' : [ 'audio1 ' , 'audio1 ' , 'audio2 ' , 'audio2 ' , 'audio3 ' , 'audio3 ' ] , 'text ' : [ 'text1 ' , 'text2 ' , 'text3 ' , 'text4 ' , 'text5 ' , 'text6 ' ] , 'login ' : [ 'operator1 ' , 'operator2 ' , 'operator3 ' , 'operator4 ' , 'operator5 ' , 'operator6 ' ] } ) x1 = x.groupby ( 'audio '... | Pandas group by result to columns |
Python | I have to take a string containing placeholders for later substitution , like : And turn that into : I came up with : That works , but it feels super clunky , and not at all `` idiomatic '' python . How would a well , idiomatic python solution look like ? Updates for clarification : the resulting strings are n't used w... | `` A % s B % s '' `` A { 0 } B { 1 } '' def _fix_substitution_parms ( raw_message ) : rv = raw_message counter = 0 while ' % s ' in rv : rv = rv.replace ( ' % s ' , ' { ' + str ( counter ) + ' } ' , 1 ) counter = counter + 1return rv | How to turn % s into { 0 } , { 1 } ... less clunky ? |
Python | I undertook an interview last week in which I learnt a few things about python I did n't know about ( or rather realise how they could be used ) , first up and the content of this question is the use of or for the purposes of branch control . So , for example , if we run : Then if f ( ) evaluates to some true condition... | def f ( ) : # do something . I 'd use ... but that 's actually a python object.def g ( ) : # something else.f ( ) or g ( ) makeeven ( N,1 ) - > N+1 ; makeeven ( N,0 ) - > N ; makeeven ( N ) - > makeeven ( N , N rem 2 ) . | Use of OR as branch control in FP |
Python | I have one dataframe df , with two columns : Script ( with text ) and SpeakerAnd I have the following list : L = [ ' a ' , ' b ' , ' c ' ] With the following code , I obtain this dataframe df2 : Which line can I add in my code to obtain , for each line of my dataframe df2 , a percentage value of all lines spoken by spe... | Script Speakeraze Speaker 1 art Speaker 2ghb Speaker 3jka Speaker 1tyc Speaker 1avv Speaker 2 bhj Speaker 1 df = ( df.set_index ( 'Speaker ' ) [ 'Script ' ] .str.findall ( '|'.join ( L ) ) .str.join ( '| ' ) .str.get_dummies ( ) .sum ( level=0 ) ) print ( df ) Speaker a b cSpeaker 1 2 1 1Speaker 2 2 0 0Speaker 3 0 1 0 ... | Calculate percentage of similar values in pandas dataframe |
Python | I 've updated django from 1.6 to 1.8.3 . I create test models in test setUp method in unit tests , something like thatAnd I have code in the application , which relies on the primary key == 1 . I 've noted , that sequences are n't actually reseted . In each next test the pk is greater , that in previous . This works ok... | class MyTestCase ( LiveServerTestCase ) : reset_sequences = True def setUp ( self ) : self.my_model = models.MyModel.objects.create ( name='test ) | Django reset_sequences does n't work in LiveServerTestCase |
Python | I have a boolean matrix with 1.5E6 rows and 20E3 columns , similar to this example : Also , I have another matrix N ( 1.5E6 rows , 1 column ) : What I need to do , is to go through each column pair from matrix M ( 1 & 1 , 1 & 2 , 1 & 3 , 1 & N , 2 & 1 , 2 & 2 etc ) combined by the AND operator , and count how many over... | M = [ [ True , True , False , True , ... ] , [ False , True , True , True , ... ] , [ False , False , False , False , ... ] , [ False , True , False , False , ... ] , ... [ True , True , False , False , ... ] ] N = [ [ True ] , [ False ] , [ True ] , [ True ] , ... [ True ] ] for i in range ( M.shape [ 1 ] ) : for j in... | Fastest way for boolean matrix computations |
Python | How could I split a string by comma which contains commas itself in Python ? Let 's say the string is : How do I make sure I only get four elements after splitting ? | object = `` '' '' { `` alert '' , `` Sorry , you are not allowed to do that now , try later '' , `` success '' , `` Welcome , user '' } '' '' '' | Regex for splitting a string which contains commas |
Python | a simple example : run with error when do current_process in __del__ : if I change a variable name : it get the right result : and I tried many variable name , some ok , some error.Why different instance name , will cause multiprocessing module be None in __del__ ? | # ! /usr/bin/env python # -*- coding : utf-8 -*-import multiprocessingclass Klass ( object ) : def __init__ ( self ) : print `` Constructor ... % s '' % multiprocessing.current_process ( ) .name def __del__ ( self ) : print `` ... Destructor % s '' % multiprocessing.current_process ( ) .nameif __name__ == '__main__ ' :... | Python strange multiprocessing with variable name |
Python | I would like to know if there is a way of writing the below module code without having to add another indentation level the whole module code.I am looking for something like this : Note , I do not want to throw an Exception , the import should pass normally . | # module codeif not condition : # rest of the module code ( big ) # module codeif condition : # here I need something like a ` return ` # rest of the module code ( big ) | Is it possible to end a python module import with something like a return ? |
Python | Many iterator `` functions '' in the __builtin__ module are actually implemented as types , even although the documentation talks about them as being `` functions '' . Take for instance enumerate . The documentation says that it is equivalent to : Which is exactly as I would have implemented it , of course . However , ... | def enumerate ( sequence , start=0 ) : n = start for elem in sequence : yield n , elem n += 1 > > > x = enumerate ( range ( 10 ) ) > > > x < generator object enumerate at 0x01ED9F08 > > > > x = enumerate ( range ( 10 ) ) > > > x < enumerate object at 0x01EE9EE0 > class enumerate : def __init__ ( self , sequence , start... | Why are some python builtin `` functions '' actually types ? |
Python | I have written a python code for a newton method in 1D and want to use it to calculate the newton fractal for the function The basic python code I am using is this : My newton ( ) -function returns the number of iterations it needed to find an approximation xk such that |f ( xk ) | < 1e-10.I tested this code with and i... | error = 1e-10resolution = 100x_range = np.linspace ( -2,2 , resolution ) y_range = np.linspace ( -1,1 , resolution ) fraktal = np.zeros ( shape= ( resolution , resolution ) ) for i in range ( resolution ) : for j in range ( resolution ) : x = x_range [ i ] y = y_range [ j ] z = complex ( x , y ) fraktal [ i , j ] = new... | newton fractal : mathoverflow error |
Python | Disclaimer : completely new to Python from a PHP backgroundOk I 'm using Python on Google App Engine with Google 's webapp framework.I have a function which I import as it contains things which need to be processed on each page.This works fine when I call it , but how can I make sure the app is killed off after the red... | def some_function ( self ) : if data [ 'user ' ] .new_user and not self.request.path == '/main/new ' : self.redirect ( '/main/new ' ) class Dashboard ( webapp.RequestHandler ) : def get ( self ) : some_function ( self ) # Continue with normal code here self.response.out.write ( 'Some output here ' ) | How can I kill off a Python web app on GAE early following a redirect ? |
Python | I was playing around with metaclasses in CPython 3.2.2 , and I noticed it is possible to end up with a class that is its own type : For our metaclass A , there does n't really seem to be much of a distinction between class and instance attributes : All this works the same ( apart from changing to __metaclass__ , and __... | Python 3.2.2 ( default , Sep 5 2011 , 21:17:14 ) [ GCC 4.6.1 ] on linux2Type `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > class MC ( type ) : # a boring metaclass that works the same as type ... pass ... > > > class A ( MC , metaclass=MC ) : # A is now both a subclass and an... | Python - an object can be its own type ? |
Python | Is there a good way to find stretches of Trues in a numpy boolean array ? If I have an array like : Can I get an array of indices like : or any other appropriate way to store this information . I know this can be done with some complicated while loops , but I 'm looking for a better way . | x = numpy.array ( [ True , True , False , True , True , False , False ] ) starts = [ 0,3 ] ends = [ 1,4 ] | find stretches of Trues in numpy array |
Python | I 've made this list ; each item is a string that contains commas ( in some cases ) and colon ( always ) : I would like to create a new list from the one above as follows : But I 'd like to know if/ how it 's possible to do so in a line or two of efficient code employing primarily Python 's higher order functions . I '... | dinner = [ 'cake , peas , cheese : No ' , 'duck , broccoli , onions : Maybe ' , 'motor oil : Definitely Not ' , 'pizza : Damn Right ' , 'ice cream : Maybe ' , 'bologna : No ' , 'potatoes , bacon , carrots , water : Yes ' , 'rats , hats : Definitely Not ' , 'seltzer : Yes ' , 'sleeping , whining , spitting : No Way ' , ... | Using Python Higher Order Functions to Manipulate Lists |
Python | I am trying to syllabify devanagari wordsधर्मक्षेत्रे - > धर् मक् षेत् रेdharmakeshetre - > dhar mak shet reI get the result as : Which is partially correctI try another word कुरुक्षेत्र - > कु रुक् षेत् रेkurukshetre - > ku ruk she treThe result is obviously wrong.How do I extract the syllables effectively ? | wd.split ( '् ' ) [ 'धर ' , 'मक ' , ' षेत ' , ' रे ' ] [ ' कुरुक ' , ' षेत ' , ' रे ' ] | Syllabification of Devanagari |
Python | Not sure how to title this question . I 've run into a few situations where I have a list of data , maybe annotated with some property , and I want to collect them into groups . For example , maybe I have a file like this : and I want to group each set of readings , splitting them on a condition ( in this case , an eve... | some eventreading : 25.4reading : 23.4reading : 25.1different eventreading : 22.3reading : 21.1reading : 26.0reading : 25.2another eventreading : 25.5reading : 25.1 [ [ 'some event ' , 'reading : 25.4 ' , 'reading : 23.4 ' , 'reading : 25.1 ' ] , [ 'different event ' , 'reading : 22.3 ' , 'reading : 21.1 ' , 'reading :... | How to collect data from a list into groups based on condition ? |
Python | Minimal exampleI tried referencing the class namespace as well but that is n't working eitherAnd of course , this works as expectedI want to understand why this scope issue is happening then , if I am trying to do something insane understand the best way to do it otherwise . My feeling was that the first code snip shou... | class foo : loadings = dict ( hi=1 ) if 'hi ' in loadings : print ( loadings [ 'hi ' ] ) # works print ( { e : loadings [ e ] for e in loadings } ) # NameError global name 'loadings ' not defined class foo : loadings = dict ( hi=1 ) if 'hi ' in loadings : print ( loadings [ 'hi ' ] ) # works print ( { e : foo.loadings ... | Python scoping issue with dictionary comprehension inside class level code |
Python | In python , I one had to swap values of 2 variables , all you need to do wasOne can look at it as if the two statements- ( x=y ) and ( y=x ) are executed in parallel and not one after another.Is there any way to achieve the same effect in c++ ? NOTE/EDIT : I am looking to extend this 'parallel effect ' ( if it exists )... | x , y=y , x | Running statements in 'parallel ' |
Python | I have the following f-string I want to print out on the condition the variable is available : Which results in : So normally I 'd use a type specifier for float precision like this : Which would result in : But that messes with the if-statement in this case . Either it fails because : The if statement becomes unreacha... | f '' Percent growth : { self.percent_growth if True else 'No data yet ' } '' Percent growth : 0.19824077757643577 f ' { self.percent_growth : .2f } ' 0.198 f '' Percent profit : { self.percent_profit : .2f if True else 'None yet ' } '' f '' Percent profit : { self.percent_profit if True else 'None yet ' : .2f } '' | How to apply float precision ( type specifier ) in a conditional f-string ? |
Python | I have an expression like thiswhich is entered into Sympy like this ( for the sake of a reproducible example in this question ) Eyeballing this expression , the first order Taylor approximation for any of the variables , e.g . k1 , around some nonzero value should be nonzero , but this codejust returns 0 . This is a pr... | from sympy import *expression = Add ( Mul ( Integer ( -1 ) , Float ( ' 0.9926375361451395 ' , prec=2 ) , Add ( Mul ( Float ( ' 0.33167082639756074 ' , prec=2 ) , Pow ( Symbol ( 'k1 ' ) , Float ( '-0.66666666666666674 ' , prec=2 ) ) , Pow ( Symbol ( 'n1 ' ) , Float ( ' 0.66666666666666674 ' , prec=2 ) ) ) , Mul ( Float ... | Why does my Sympy code calculate the first order Taylor series approximation incorrectly ? |
Python | I 'm working with a mapping from values of a python dictionary into a numpy array like this : This offers the values referenced through the dict to reflect any changes made in the full array . I need the size of the groups within the dict to be flexible . However when a group is only a single element , such as : ... th... | import numpy as npmy_array = np.array ( [ 0 , 1 , 2 , 3 , 4 , 5 , 6 ] ) my_dict = { 'group_a ' : my_array [ 0:3 ] , 'group_b ' : my_array [ 3 : ] } my_dict2 = { 'group_a ' : my_array [ 0 ] , 'group_b ' : my_array [ 1 : ] } | Numpy - retaining the pointer when referencing a single element |
Python | I am trying to learn python and I landed on the with..asconstruct , that used like this : So as a learning strategy I tried to do the following : and I got this output : My question is then : why did print ( derived ) return a None object and not a Derived object ? | with open ( `` somefile.txt '' , 'rt ' ) as file : print ( file.read ( ) ) # at the end of execution file.close ( ) is called automatically . class Derived ( ) : def __enter__ ( self ) : print ( '__enter__ ' ) def __exit__ ( self , exc_type , exc_value , traceback ) : print ( '__exit__ ' ) with Derived ( ) as derived :... | Trying to figure out how the 'with..as ' construct works in python |
Python | I have a ID terminatorand a .txt sample file to parseI generated Java and Python2 target and test each against sample file respectively . Java target can parse this file . But Python2 target ca n't . It throws token recognition error at : ' 均 ' . And I tested Python2 target against other valid inputs , all works except... | ID : ( [ A-Z_ ] |'\u0100'..'\uFFFE ' ) ( [ A-Z_0-9 ] |'\u0100'..'\uFFFE ' ) * ; 均60 : =MA ( C,60 ) ; mkdir -p javajava -jar /usr/local/lib/antlr-4.5.3-complete.jar TDX.g4 -o ./javacd ./javajavac TDX*.javajava org.antlr.v4.gui.TestRig TDX prog -gui ../samples/1.txt java -jar /usr/local/lib/antlr-4.5.3-complete.jar -Dlan... | antlr4 python target can not recognize unicode |
Python | i am trying to implement my own version of a DailyLogFile but it looks like i miss a fundamental of Python subclassing process ... as i get this error : so i need to explicitly add and define others methods like Write and rotate method like this : while i thought it would be correctly inherit from the base mother class... | from twisted.python.logfile import DailyLogFileclass NDailyLogFile ( DailyLogFile ) : def __init__ ( self , name , directory , rotateAfterN = 1 , defaultMode=None ) : DailyLogFile.__init__ ( self , name , directory , defaultMode ) # why do not use super . here ? lisibility maybe ? # self.rotateAfterN = rotateAfterN def... | Python : why a method from super class not seen ? |
Python | I have a list of dicts and would like to design a function to output a new dict which contains the sum for each unique key across all the dicts in the list.For the list : So far so good , this can be done with a counter : Which correctly returns : The trouble comes when the dicts in my list start to contain nested dict... | [ { 'apples ' : 1 , 'oranges ' : 1 , 'grapes ' : 2 } , { 'apples ' : 3 , 'oranges ' : 5 , 'grapes ' : 8 } , { 'apples ' : 13 , 'oranges ' : 21 , 'grapes ' : 34 } ] def sumDicts ( listToProcess ) : c = Counter ( ) for entry in listToProcess : c.update ( entry ) return ( dict ( c ) ) { 'apples ' : 17 , 'grapes ' : 44 , '... | Python sum list of dicts by key with nested dicts |
Python | Assume we have the following simplified data : I want to enumerate columns with the same prefix . In this case the prefixes are Data , Text . So expected output would be : Note the enumerated columns.Attempted solution # 1 : Attempted solution # 2 : Question : Is there an easier solution to do this , I also looked at d... | df = pd.DataFrame ( { ' A ' : list ( 'abcd ' ) , ' B ' : list ( 'efgh ' ) , 'Data_mean ' : [ 1,2,3,4 ] , 'Data_std ' : [ 5,6,7,8 ] , 'Data_corr ' : [ 9,10,11,12 ] , 'Text_one ' : [ 'foo ' , 'bar ' , 'foobar ' , 'barfoo ' ] , 'Text_two ' : [ 'bar ' , 'foo ' , 'barfoo ' , 'foobar ' ] , 'Text_three ' : [ 'bar ' , 'bar ' ,... | Enumerate columns with same prefix |
Python | I am working on old text files with 2-digit years where the default century logic in dateutil.parser does n't seem to work well . For example , the attack on Pearl Harbor was not on dparser.parse ( `` 12/7/41 '' ) ( which returns 2041-12-7 ) . The buit-in century `` threshold '' to roll back into the 1900 's seems to h... | import dateutil.parser as dparserprint ( dparser.parse ( `` 12/31/65 '' ) ) # goes forward to 2065-12-31 00:00:00print ( dparser.parse ( `` 1/1/66 '' ) ) # goes back to 1966-01-01 00:00:00 | customize dateutil.parser century inference logic |
Python | I was messing around while trying to figure out shallow and deep copying in Python , and noticed that while the identities of a copied set , list , or seemingly any mutable type are n't the same : For immutable types this is n't the case - it looks like a copy points to the same address in memory . This sort of intuiti... | In [ 2 ] : x1 = { 1,2,3 } In [ 3 ] : x2 = x1.copy ( ) In [ 4 ] : x1 is x2Out [ 4 ] : False In [ 6 ] : f1 = frozenset ( { 1,2,3 } ) In [ 7 ] : f2 = f1.copy ( ) In [ 8 ] : f1 is f2Out [ 8 ] : True In [ 11 ] : t1 = tuple ( ( 1 , [ ' a ' , ' b ' ] ) ) In [ 12 ] : t2 = tuple ( t1 ) # I would expect an actual copy , but it i... | I think immutable types like frozenset and tuple not actually copied . What is this called ? Does it have any implications ? |
Python | In python3 , when I try to execute the following lines : Why does python throw that in my opinion highly misleading TypeError : format ( ) argument after * must be a sequence , not map for this builtin function ? It makes it even more confusing to see that an explicit raise for other Exceptions is caught an passed thro... | $ python3Python 3.3.5 ( default , Mar 18 2014 , 02:00:02 ) [ GCC 4.2.1 20070831 patched [ FreeBSD ] ] on freebsd9Type `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > def fail ( arg ) : ... raise Exception ... > > > def fail_type ( arg ) : ... raise TypeError ... > > > identity ... | Sometimes , map is a sequence , sometimes not ? |
Python | I am trying to reproduce the algorithm explained here in Python but I am facing some problems with a strange growth of some parameters.The following is my attempt . Observe that get_ang ( ) and get_acc ( ) return angular velocity and acceleration along [ x , y , z ] -axis in degrees/s ( but I convert this data in radia... | import numpy as npimport quaternionfrom utils import get_ang , get_acc # utilsZ=np.zeros ( [ 3,3 ] ) I=np.eye ( 3 ) EARTH_GRAVITY_MS2 = -9.80665 # sample parametersN=1 # DecimationFactorfs=10 # SampleRate # noise parametersbeta=3.0462e-13 # GyroscopeDriftNoiseeta=9.1385e-5 # GyroscopeNoisekappa=N/fs # DecimationFactor/... | Error state Kalman Filter from MATLAB to Python |
Python | A reoccurring pattern in my Python programming on GAE is getting some entity from the data store , then possibly changing that entity based on various conditions . In the end I need to .put ( ) the entity back to the data store to ensure that any changes that might have been made to it get saved . However often there w... | def handle_get_request ( ) : entity = Entity.get_by_key_name ( `` foobar '' ) if phase_of_moon ( ) == `` full '' : entity.werewolf = True if random.choice ( [ True , False ] ) : entity.lucky = True if some_complicated_condition : entity.answer = 42 entity.put ( ) def handle_get_request ( ) : entity = Entity.get_by_key_... | Elegant way to avoid .put ( ) on unchanged entities |
Python | I 'm OCRing some text from two different sources . They can each make mistakes in different places , where they wo n't recognize a letter/group of letters . If they do n't recognize something , it 's replaced with a ? . For example , if the word is Roflcopter , one source might return Ro ? copter , while another , Rofl... | match ( `` Ro ? copter '' , `` Roflcop ? er '' ) -- > Truematch ( `` Ro ? copter '' , `` Roflcopter '' ) -- > Truematch ( `` Roflcopter '' , `` Roflcop ? er '' ) -- > Truematch ( `` Ro ? co ? er '' , `` Roflcop ? er '' ) -- > True > > > def match ( tn1 , tn2 ) : tn1re = tn1.replace ( `` ? `` , `` . { 0,4 } '' ) tn2re =... | elegant way to match two wildcarded strings |
Python | Here is the code I am usingWhich is giving me the following error : I am hoping to 1 ) understand why this is happening , and 2 ) find a solution that allows me to pickle the object ( without removing the memoization ) . Ideally the solution would not change the call to pickle . Running python 3.6 with funcy==1.10 | import funcy @ funcy.memoizeclass mystery ( object ) : def __init__ ( self , num ) : self.num = numfeat = mystery ( 1 ) with open ( 'num.pickle ' , 'wb ' ) as f : pickle.dump ( feat , f ) PicklingError : Ca n't pickle < class '__main__.mystery ' > : it 's not the same object as __main__.mystery | Cant Pickle memoized class instance |
Python | I am going through the examples mentioned here , and am looking at this example . I ran a sample example below on ipython , and the result is consistent , i.e. , `` % d '' is slower than `` % s '' : Both the code blocks are similar , and even the output of disassembler is same , so why is `` % s '' faster than `` % d '... | In [ 1 ] : def m1 ( ) : ... : return `` % d '' % ( 2*3/5 ) In [ 2 ] : def m2 ( ) : ... : return `` % s '' % ( 2*3/5 ) In [ 4 ] : % timeit m1 ( ) 1000000 loops , best of 3 : 529 ns per loopIn [ 5 ] : % timeit m2 ( ) 1000000 loops , best of 3 : 192 ns per loopIn [ 6 ] : from dis import disIn [ 7 ] : dis ( m1 ) 2 0 LOAD_C... | Why is % s faster than % d for integer substitution in python ? |
Python | I see no difference in sub classing the models.manager object and overriding the get_query_set method or simply creating a new method in the sub class and using the method . For the reason being I have taken example from the django book ; With this I could use ; Person.women.all ( ) or Person.men.all ( ) to fetch all t... | class MaleManager ( models.Manager ) : def get_query_set ( self ) : return super ( MaleManager , self ) .get_query_set ( ) .filter ( sex='M ' ) class FemaleManager ( models.Manager ) : def get_query_set ( self ) : return super ( FemaleManager , self ) .get_query_set ( ) .filter ( sex= ' F ' ) class Person ( models.Mode... | subclassing models.Manager |
Python | Is there an existing Emacs function that adds the symbol currently under the point to __all__ when editing Python code ? E.g. , say the cursor was on the first o in foo : If you did M-x python-add-to-all ( or whatever ) it would add 'foo ' to __all__.I did n't see one when I googled around , but , as always , maybe I '... | # v -- -- cursor is on that ' o'def foo ( ) : return 42 ( defun python-add-to-all ( ) `` Take the symbol under the point and add it to the __all__list , if it 's not already there . '' ( interactive ) ( save-excursion ( let ( ( thing ( thing-at-point 'symbol ) ) ) ( if ( progn ( goto-char ( point-min ) ) ( let ( found ... | Emacs function to add symbol to __all__ in Python mode ? |
Python | I tried my attempt at finding the smallest number that is divisible by numbers from 1 to n , and now I 'm looking for advice on ways to further compact/make my solution more efficient . It would be pretty cool if there was an O ( 1 ) solution too . | def get_smallest_number ( n ) : `` '' '' returns the smallest number that is divisible by numbers from 1 to n `` '' '' divisors = range ( 1 , n+1 ) check_divisible = lambda x : all ( [ x % y == 0 for y in divisors ] ) i = 1 while True : if check_divisible ( i ) : return i i += 1 | Fastest and most compact way to get the smallest number that is divisible by numbers from 1 to n |
Python | Given a path , e.g . I wish to remove the e.This is what I did : Any more elegant way to do it ? | file_path = ' a.b.c.d.e ' class_path = ( '. ' ) .join ( file_path.split ( ' . ' ) [ 0 : -1 ] ) | Remove a part of a path separated with dots |
Python | Here is my model : Essentially , what I want is is for other_model to be unique in this table . That means that if there is a record where other_model_one id is 123 , I should not allow another record to be created with other_model_two id as 123 . I can override clean I guess but I was wondering if django has something... | class GroupedModels ( models.Model ) : other_model_one = models.ForeignKey ( 'app.other_model ' ) other_model_two = models.ForeignKey ( 'app.other_model ' ) | Is there a way to create a unique id over 2 fields ? |
Python | I 'm trying to achieve the behavior above . Read further if you care why or if the example is n't sufficient enough . Sorry for the sharp tongue , but most of my Stack Exchange questions get hostile questions back instead of answers.This question arises from requiring an admin to run my script , but the nature of the s... | [ root @ hostname ~ ] # python script.py # allow this [ user @ hostname ~ ] $ sudo python script.py # deny this [ user @ hostname ~ ] $ sudo -E python script.py # deny this [ user @ hostname ~ ] $ sudo PATH= $ PATH python script.py # deny this [ user @ hostname ~ ] $ python script.py # kindly refuse this if os.geteuid ... | Can my Python script distinguish between if it was run as root or if it was run through sudo ? |
Python | The Python documentation about the is operator says : The operators is and is not test for object identity : x is y is true if and only if x and y are the same object . x is not y yields the inverse truth value.Let 's try that : The Python documentation also says : Due to automatic garbage-collection , free lists , and... | > > > def m ( ) : ... pass ... > > > m is mTrue > > > class C : ... def m ( ) : ... pass ... > > > C.m is C.mFalse | Why is a method not identical to itself ? |
Python | I have a dataset that looks something like this : That is then being computed into this to create a kmeans cluster.What I want to do is to make those clusters relate to both time periods and keys.With the time periods -7 am to 10 am , and 4 pm to 6 pm , and 12 pm to 2 pm , with 6 pm to 12 am , 12 am to 7 am , and 10 am... | date area_key total_units timeatend starthour timedifference vps2020-01-15 08:22:39 0 9603 2020-01-15 16:32:39 8 29400.0 0.326632653061224462020-01-13 08:22:07 0 10273 2020-01-13 16:25:08 8 28981.0 0.354473620648010752020-01-23 07:16:55 3 5175 2020-01-23 14:32:44 7 26149.0 0.197904317564725242020-01-15 07:00:06 1 838 2... | How to group a dataframe by 4 time periods and key |
Python | As I am sure you are well aware , python , as do most programming languages , comes with built-in exceptions . I have gone through the list , and can not deduce which would be appropriate . Of course I can make my own exception , but this is a fairly standard error that would be excepted.This is an error based on insta... | class Foo : def __init__ ( self , related=None ) : `` 'related is a list of Foo instances '' ' if related is not None : self.related = related else : self.related = [ ] def compute ( self , instance ) : if instance in self.related : # execute code else : raise SomeError ( `` You can not make a computation with an unrel... | Python which built in exception to use |
Python | If a = 15 and 152 is represented as a2 while 215 is represented as 2a then a number x has to be found such that8x = 8*x8I tried this naive Python codebut it is taking a huge amount of time to produce a correct result.How to optimize the code ? | > > > i = 0 > > > while ( i < =100000000000000000 ) : ... if ( int ( `` 8 '' +str ( i ) ) ==8*int ( str ( i ) + '' 8 '' ) ) : ... break ... i = i+1 ... print i | Efficiently solving a letter/number problem in Python |
Python | I 've looked at several other SO questions ( and google 'd tons ) that are 'similar'-ish to this , but none of them seem to fit my question right.I am trying to make a non fixed length , unique text string , only containing characters in a string I specify . E.g . made up of capital and lower case a-zA-Z characters . (... | def next ( index , validCharacters = 'abc ' ) : return uniqueShortAsPossibleString next ( 1 ) == ' a'next ( 2 ) == ' b'next ( 3 ) == ' c'next ( 4 ) == 'aa'next ( 5 ) == 'ab'next ( 6 ) == 'ac'next ( 7 ) == 'ba'next ( 8 ) == 'bb'next ( 9 ) == 'bc'next ( 10 ) == 'ca'next ( 11 ) == 'cb'next ( 12 ) == 'cc ' | python unique string creation |
Python | I 'd like to know if its possible to use the * operator in a oneline if to achieve the following functionality : I thought I could just saybut it turns out this is the same as saying which does n't make any sense for *None . I tired enclosing the first option in parenthesis but this just throws SyntaxError : ca n't use... | if node [ 'args ' ] ! = None : return_val = funct ( *node [ 'args ' ] ) else : return_val = funct ( ) return_val = funct ( *node [ 'args ' ] if node [ 'args ' ] ! = None else None ) if node [ 'args ' ] ! = None : return_val = funct ( *node [ 'args ' ] ) else : return_val = funct ( *None ) return_val = funct ( ( *node [... | Proper use of the * operator in a oneline if statement python |
Python | I am using jupyter-cadquery to visualize some 3D models made with CadQuery.When visualizing the models on a Jupyter notebook , everything works as expected.But when trying to embed the widget in an HTML document , it seems the camera , on load , is pointing to ( 0 , 0 , 0 ) , not as expected . Once you interact with th... | from cadquery import Workplanefrom ipywidgets import embedfrom jupyter_cadquery.cad_view import CadqueryViewfrom jupyter_cadquery.cadquery import Assemblyfrom jupyter_cadquery.cadquery import Part # Create a simple assemblybox1 = Workplane ( 'XY ' ) .box ( 10 , 10 , 10 ) .translate ( ( 0 , 0 , 5 ) ) a1 = Assembly ( [ P... | Embed widgets with jupyter-cadquery ( threejs ) : wrong position on load |
Python | I only have OOP programming experience in Java and have just started working on a project in Python and I 'm starting to realize Python makes me skeptical about a few things that are intuitive to me . So I have a few questions about OOP in Python.Scenario : I 'm writing a program that will send emails . For an email , ... | class Mailer ( object ) : __metaclass__ == abc.ABCMeta def __init__ ( self , key ) : self.key = key @ abc.abstractmethod def send_email ( self , mailReq ) : passclass MailGunMailer ( Mailer ) : def __init__ ( self , key ) : super ( MailGunMailer , self ) .__init__ ( key ) def send_email ( self , mailReq ) : from = mail... | Python OOP from a Java programmer 's perspective |
Python | I would like to have python logging output to be in form of tree corresponding to logger tree . Just look at example.Lets say we have a code : The output should be something like : I could write formatters for each of the log by hand , but it does n't solve the problem of inserting something like o < -- '' a.b '' right... | import logginglogger_a = logging.getLogger ( `` a '' ) logger_a_b = logging.getLogger ( `` a.b '' ) logger_a_b_c = logging.getLogger ( `` a.b.c '' ) # ... logger_a.debug ( `` One '' ) logger_a_b.warning ( `` two '' ) logger_a_b.warning ( `` three '' ) logger_a_b_c.critical ( `` Four '' ) logger_a_b.warning ( `` Five ''... | Format log messages as a tree |
Python | Here 's a simple class created declaratively : And here 's a similar class , but it was defined by invoking the metaclass manually : I 'm interested to know whether they are indistinguishable . Is it possible to detect such a difference from the class object itself ? | class Person : def say_hello ( self ) : print ( `` hello '' ) def say_hello ( self ) : print ( `` sayolala '' ) say_hello.__qualname__ = 'Person.say_hello'TalentedPerson = type ( 'Person ' , ( ) , { 'say_hello ' : say_hello } ) > > > def was_defined_declaratively ( cls ) : ... # dragons ... > > > was_defined_declarativ... | Detect if class was defined declarative or functional - possible ? |
Python | Given the example below , which is more pythonic ? Using function composition , lambdas , or ( now for ) something completely different ? I have to say that the lambdas seem to be more readable , but Guido himself seems to want to remove lambdas altogether - http : //www.artima.com/weblogs/viewpost.jsp ? thread=98196 | from functools import partialfrom operator import not_ , gedef get_sql_data_type_from_string ( s ) : s = str ( s ) # compose ( *fs ) - > returns composition of functions fs # iserror ( f , x ) - > returns True if Exception thrown from f ( x ) , False otherwise # Using function composition predicates = ( ( 'int ' , comp... | What is more pythonic - function composition , lambdas , or something else ? |
Python | In KDE 5 ( Kubuntu 15.04 / Plasma 5.2 ) disabled Qt-Buttons ( Qt4 ) are indistinguishable from non-disabled buttons . This problem does not exist in KDE 4.14 as the following screen-shot shows : The program source for this dialog is written in Python with PyQt4 : How can I make disabled Buttons in KDE 5 recognizable ? ... | from PyQt4 import QtGuiimport sysif __name__ == `` __main__ '' : # main function app = QtGui.QApplication ( sys.argv ) qw = QtGui.QWidget ( ) qw.resize ( 150 , 120 ) qw.setWindowTitle ( `` KDE 4 '' ) # qw.setWindowTitle ( `` KDE 5 '' ) b1 , b2 = QtGui.QPushButton ( qw ) , QtGui.QPushButton ( qw ) for b , y , e in zip (... | Disabled Qt-Buttons are not shown as disabled in Plasma 5.2 ( KDE 5 ) |
Python | I 'm trying to optimise an exponential objective function with GEKKO , but I do n't know if the selected solver is the best one for these kind of problems . Is the selected one a valid choice ? ? | import numpy as np'GEKKO MODELING'from gekko import GEKKOm = GEKKO ( ) m.options.SOLVER=1 # APOPT is an MINLP solver # Initialize variablesx = [ ] x1 = m.Var ( value=20 , lb=20 , ub=6555 ) # integer=Truex2 = m.Var ( value=0 , lb=0 , ub=10000 ) # integer=Truex3 = m.sos1 ( [ 30 , 42 , 45 , 55 ] ) x = [ x1 , x2 , x3 ] # E... | What solver should I use if my objective function is an nonlinear ( also exponential explanation ) function ? Python GEKKO |
Python | I want to compare all CSV files kept on my local machine to files kept on a server . The folder structure is the same for both of them . I only want to do a data comparison and not metadata ( like time of creation , etc ) . I am using filecmp but it seems to perform metadata comparison . Is there a way to do what I wan... | import filecmpcomparison = filecmp.dircmp ( dir_local , dir_server ) comparison.report_full_closure ( ) | Compare CSV files content with filecmp and ignore metadata |
Python | I 've been subclassing tuple or using namedtuple blissfully for a few years , but now I have a use case where I need a class that can be used as a weak referent . And today I learned tuples do n't support weak references . Is there another way to create an immutable object in Python with a fixed set of attributes ? I d... | class SimpleThingWithMethods ( object ) : def __init__ ( self , n , x ) : # I just need to store n and x as read-only attributes ... ? ? ? ... | immutable objects in Python that can have weak references |
Python | I was solving problem 26 on Project Euler where I need to calculate the length of the recurring part of 1/n where n is all integers between 1 and 1000 , and see which number makes the longest recurring part . That meant that I needed my division done a lot more precisely . So I was playing around with my decimal precis... | import reimport times = time.time ( ) from decimal import *getcontext ( ) .prec = 500 # This partrecurring = 0answer = 0p = re.compile ( r '' ( [ 0-9 ] + ? ) \1 { 3 , } '' ) for i in range ( 1 , 1000 ) : f = p.search ( str ( Decimal ( 1 ) / Decimal ( i ) ) [ 5 : ] ) if f : number = f.group ( 1 ) if len ( str ( number )... | Why does increasing precision make this program faster ? |
Python | I stumbled upon this line of code in SciPy 's source , in the stats module : Is this return something other than 1.0 ? In other words , is there any value of x such that x == x holds False ? | return 1.0* ( x==x ) | Is x==x ever False in Python ? |
Python | I 'm getting the following error on the second refresh of a page : DetachedInstanceError : Instance is not bound to a Session ; attribute refresh operation can not proceedThe issue seems to be some sharing of cached data between requests . The thing is that it 's only supposed to be cached locally ( i.e . re-query ever... | DetachedInstanceError : Instance < MetadataRef at 0x107b2a0d0 > is not bound to a Session ; attribute refresh operation can not proceed - Expression : `` result.meta_refs ( visible_search_only=True ) '' - Filename : ... ects/WebApps/PYPanel/pypanel/templates/generic/search.pt - Location : ( line 45 : col 38 ) - Source ... | Python ( Pyramid framework ) is persisting data between requests and I ca n't figure out why |
Python | I have a list of characters and list of indexesand I 'd like to get this in one operationI could do this but is there is a way to do it faster ? | myList = [ ' a ' , ' b ' , ' c ' , 'd ' ] toRemove = [ 0,2 ] myList = [ ' b ' , 'd ' ] toRemove.reverse ( ) for i in toRemove : myList.pop ( i ) | Concise way to remove elements from list by index in Python |
Python | Problem statementI 'm looking for an efficient way to generate full binary cartesian products ( tables with all combinations of True and False with a certain number of columns ) , filtered by certain exclusive conditions . For example , for three columns/bits n=3 wewould get the full tableThis is supposed to be filtere... | df_combs = pd.DataFrame ( itertools.product ( * ( [ [ True , False ] ] * n ) ) ) 0 1 20 True True True1 True True False2 True False True3 True False False ... mutually_excl = [ { 0 : False , 1 : False , 2 : True } , { 0 : True , 2 : True } ] 0 1 21 True True False3 True False False4 False True True5 False True False7 F... | Generate filtered binary cartesian products |
Python | Hi I am working on implementing a multi-classification model ( 5 classes ) with the new SpaCy Model en_pytt_bertbaseuncased_lg . The code for the new pipe is here : The code for the training is as follows and is based on the example from here ( https : //pypi.org/project/spacy-pytorch-transformers/ ) : So the structure... | nlp = spacy.load ( 'en_pytt_bertbaseuncased_lg ' ) textcat = nlp.create_pipe ( 'pytt_textcat ' , config= { `` nr_class '' :5 , `` exclusive_classes '' : True , } ) nlp.add_pipe ( textcat , last = True ) textcat.add_label ( `` class1 '' ) textcat.add_label ( `` class2 '' ) textcat.add_label ( `` class3 '' ) textcat.add_... | Model ( ) got multiple values for argument 'nr_class ' - SpaCy multi-classification model ( BERT integration ) |
Python | I have the following code copied from github gtfs_SQL_importer : I tried to run this on windows and replaced the call to the UNIX-command cat by the windows equivalent type which should work similar as of is-there-replacement-for-cat-on-windows.However when I execute that code I get some error : the syntax for the file... | cat gtfs_tables.sql \ < ( python import_gtfs_to_sql.py path/to/gtfs/data/directory ) \ gtfs_tables_makeindexes.sql \ vacuumer.sql \ | psql mydbname type < ( C : /python27/python path/to/py-script.py path/to/file-argument ) | psql -U myUser -d myDataBase C : /python27/python path/to/py-script.py path/to/file-argument | how to pipe multiple sql- and py-scripts |
Python | I have been using a wrapper for a c++-class for exporting functions to python for a while on linux . Now I wanted to make this available to my coworkers using windows . However , I fail to create a usable boost_python dll for this in cygwin . The problem arises when trying to link a dependent module in another dll , if... | # include < python2.7/Python.h > # include < boost/python.hpp > # include < boost/python/suite/indexing/vector_indexing_suite.hpp > # include `` submodule.hpp '' using namespace boost : :python ; using namespace testspace ; using namespace std ; struct cModuleB : public SubModuleClass { cModuleB ( string name , bool bo... | Linking c++-class for boost_python in cygwin |
Python | I have a pointAnd a pandas dataframeI would like to calculate the distance of every row in the pandas dataframe , to that specific pointI triedMy solution is really slow though ( taking into account that I want to calculate the distance from other points as well.Is there a way to do my calculations more efficiently ? | point = np.array ( [ 0.07852388 , 0.60007135 , 0.92925712 , 0.62700219 , 0.16943809 , 0.34235233 ] ) a b c d e f0 0.025641 0.554686 0.988809 0.176905 0.050028 0.3333331 0.027151 0.520914 0.985590 0.409572 0.163980 0.4242422 0.028788 0.478810 0.970480 0.288557 0.095053 0.9393943 0.018692 0.450573 0.985910 0.178048 0.118... | How to calculate distance for every row in a pandas dataframe from a single point efficiently ? |
Python | Produces instances smaller than those of a `` normal '' class . Why is this ? Source : David Beazley 's recent tweet . | class Spam ( object ) : __slots__ = ( '__dict__ ' , ) | Why does __slots__ = ( '__dict__ ' , ) produce smaller instances ? |
Python | In octave , all the numerical output subsequent to the command format bit will show the native bit representation of numbers as stored in the memory . For example , Is there an equivalent command in python to show all the numbers in their native-bit representation ( so the output is as shown below ) ? ( This is very di... | octave:1 > format bitoctave:2 > 0.5ans = 0011111111100000000000000000000000000000000000000000000000000000octave:7 > 2ans = 0100000000000000000000000000000000000000000000000000000000000000octave:3 > formatoctave:4 > 0.5ans = 0.50000 > > > `` equivalent of the octave format bit command '' > > > 0.500111111111000000000000... | Is there a python equivalent of the octave command ` format bit ` ? |
Python | Do Python 's stylistic best practices apply to scientific coding ? I am finding it difficult to keep scientific Python code readable.For example , it is suggested to use meaningful names for variables and to keep the namespace ordered by avoiding import * . Thus , e.g . : But these suggestions can lead to some difficul... | import numpy as np normbar = np.random.normal ( mean , std , np.shape ( foo ) ) net [ `` weights '' ] [ ix1 ] [ ix2 ] += lrate * ( CD / nCases - opts [ `` weightcost_pretrain '' ] .dot ( net [ `` weights '' ] [ ix1 ] [ ix2 ] ) ) net [ `` weights '' ] [ ix1 ] [ ix2 ] += lrate * ( CD / nCases - opts [ `` weightcost_pretr... | Readability of Scientific Python Code ( Line Continuations , Variable Names , Imports ) |
Python | I thought int in python is represented by 4 bytes , why is it reporting 12 bytes Please someone explain why is it reporting 12 bytes when int uses just 4 bytes | > > > sys.getsizeof ( int ) 436 # ? does this mean int occupies 436 bytes . > > > sys.getsizeof ( 1 ) 12 # 12 bytes for int object , is this the memory requirement . | How can i determine the exact size of a type used by python |
Python | I have an Excel ( .xlsx ) file that has two columns of phrases . For example : I want to import it in Python and to get a list of tuples like : What could I do ? | John I have a dog Mike I need a catNick I go to school [ ( 'John ' , ' I have a dog ' ) , ( 'Mike ' , ' I need a cat ' ) , ( 'Nick ' , ' I go to school ' ) , ... ] | From Excel to list of tuples |
Python | I have a csv file that has 25000 rows . I want to put the average of every 30 rows in another csv file.I 've given an example with 9 rows as below and the new csv file has 3 rows ( 3 , 1 , 2 ) : What I did : This works well but can this code be better ? | | H | ========| 1 | -- -\| 3 | | -- - > | 3 || 5 | -- -/| -1 | -- -\| 3 | | -- - > | 1 || 1 | -- -/| 0 | -- -\| 5 | | -- - > | 2 || 1 | -- -/ import numpy as npimport pandas as pdm_path = `` file.csv '' m_df = pd.read_csv ( m_path , usecols= [ 'Col-01 ' ] ) m_arr = np.array ( [ ] ) temp = m_df.to_numpy ( ) step = 30for... | Calculate average of every n rows from a csv file |
Python | Here is the code I tried : I have tried modifying the neural network and double-cheking the data.Is there anything I can do to improve the outcome ? Is the model not deep enough ? Is there any alternative models suited for my data ? Does this mean these features have no predictive value ? I 'm kind of confused what to ... | # normalizing the train datacols_to_norm = [ `` WORK_EDUCATION '' , `` SHOP '' , `` OTHER '' , 'AM ' , 'PM ' , 'MIDDAY ' , 'NIGHT ' , 'AVG_VEH_CNT ' , 'work_traveltime ' , 'shop_traveltime ' , 'work_tripmile ' , 'shop_tripmile ' , 'TRPMILES_sum ' , 'TRVL_MIN_sum ' , 'TRPMILES_mean ' , 'HBO ' , 'HBSHOP ' , 'HBW ' , 'NHB... | keras accuracy does n't improve more than 59 percent |
Python | How can I `` steal '' or copy a method from one class onto another class ? Example code : Expected output : Instead : TypeError : unbound method foo ( ) must be called with A instance as first argument ( got nothing instead ) | class A ( object ) : def foo ( self ) : print `` blah '' class B ( object ) : foo = A.fooB ( ) .foo ( ) `` blah '' | python method stealer |
Python | Is there a comprehensive reference list of the generic setup import step names ? The names of generic setup import steps do n't always match the names of their corresponding xml files for example 'types.xml ' has an import step called 'typeinfo'.In the absence of a list , I would be satisfied with a simple approach to ... | from Products.CMFCore.utils import getToolByNamePROFILE_ID = 'profile-my.package : default'setup = getToolByName ( context , 'portal_setup ' ) setup.runImportStepFromProfile ( PROFILE_ID , 'registry ' ) ValueError : No such import step : registry | Is there a good reference list for the names of the genericsetup import steps |
Python | Warning , this is a bit recursive ; ) I answered this question : Python : How can i get all the elements in a list before the longest element ? And after I submitted there where another answer that should be faster ( the author thought , and so did I ) . I tried to time the different solutions but the solution that sho... | import stringimport randomimport timedef solution1 ( lst ) : return lst [ : lst.index ( max ( lst , key=len ) ) ] def solution2 ( lst ) : idx , maxLenStr = max ( enumerate ( lst ) , key=lambda x : len ( x [ 1 ] ) ) return lst [ : idx ] # Create a 100000 elements long list that contains # random data and random element ... | Timing functions |
Python | I 've got a performance bottleneck . I 'm computing the column-wise mean of large arrays ( 250 rows & 1.3 million columns ) , and I do so more than a million times in my application . My test case in Python : Numpy takes around 400 milliseconds on my machine , running on a single core . I 've tried several other matrix... | import numpy as npbig_array = np.random.random ( ( 250 , 1300000 ) ) % timeit mean = big_array.mean ( axis = 0 ) # ~400 milliseconds | High performance array mean |
Python | I 've used Python for many years but only gradually studied the more obscure features of the language , as most of my code is for data processing . Generators based on yield are part of my routine toolkit , and recently I read about coroutines . I found an example similar to this : which prints the average of the value... | def averager ( ) : sum = 0.0 n = 0 while True : value = yield sum += value n += 1 print ( sum/n ) avg = averager ( ) next ( avg ) # prime the coroutineavg.send ( 3 ) avg.send ( 4 ) avg.send ( 5 ) | Converting from generator-based to native coroutines |
Python | My UploadForm class : HTML Templatehosts.py to run the check for validationUsing VS 's debugging tools , I find that form.validate_on_submit ( ) does n't work and always fails validation and I get this error on my html page . { 'roomImage ' : [ 'File was empty ! ' ] } There is another MultipleFileField control with alm... | from app import app from flask_wtf.file import FileRequired , FileAllowed from wtforms.fields import MultipleFileField from wtforms.validators import InputRequired , DataRequired class UploadForm ( FlaskForm ) : . . . roomImage = MultipleFileField ( 'Room ' , validators= [ FileAllowed ( [ 'jpg ' , 'png ' ] , 'Image onl... | FileRequiredValidator ( ) does n't work when using MultipleFileField ( ) in my form |
Python | I 'm trying to split a list of strings into a list of tuples of uneven length containing these strings , with each tuple containing strings initially separated with blank strings . Basically I 'd need the parameterized split that I could apply to lists . If my initial list looks like : The last element of this list is ... | init = [ ' a ' , ' b ' , `` , ' c ' , 'd e ' , 'fgh ' , `` , 'ij ' , `` , `` , ' k ' , ' l ' , `` ] end = [ ( ' a ' , ' b ' ) , ( ' c ' , 'd e ' , 'fgh ' ) , ( 'ij ' , ) , ( ' k ' , ' l ' ) ] end = [ ] while init [ -1 ] == u '' : init.pop ( ) l = [ ] while init [ -1 ] ! = u '' : l.append ( init.pop ( ) ) end.append ( t... | Splitting a list into uneven tuples |
Python | So I looked at a bunch of posts on Pyspark , Jupyter and setting memory/cores/executors ( and the associated memory ) .But I appear to be stuck -Question 1 : I dont see my machine utilizing either the cores or the memory . Why ? Can I do some adjustments to the excutors/cores/memory to optimize speed of reading the fil... | from pyspark.sql import SparkSession spark = SparkSession \ .builder \ .appName ( `` Summaries '' ) \ .config ( `` spark.some.config.option '' , `` some-value '' ) \ .getOrCreate ( ) conf = spark.sparkContext._conf.setAll ( [ ( 'spark.executor.memory ' , '4g ' ) , ( 'spark.app.name ' , 'Spark Updated Conf ' ) , ( 'spar... | PySpark : Setting Executors/Cores and Memory Local Machine |
Python | I wanted to check if a given x lies in the interval [ 0 , a-1 ] .As a lazy coder I wrote and ( because that piece of code was in 4.5 nested loops ) quickly run into performance issues . I tested it and indeed , it turns out runtime of n in range ( n ) lies in O ( n ) , give or take . I actually thought my code would be... | x in range ( a ) i = range ( a ) ... x in i | ` in range ` construction in python 2 -- - working too slow |
Python | I am using pytest with pycharm , but when I run the test , I get the test and results garbled within the pycharm console , here is an example output : This is rather not pretty , and the result are printed after the test functions report . This is how it should look like when I run pytest from the terminal : Is there a... | ============================= test session starts ==============================platform linux -- Python 3.6.6 , pytest-4.0.1 , ... .cachedir : .pytest_cacherootdir : ... .collecting ... collected 14 itemstests/test_ops.py : :test_layer tests/test_ops.py : :test_layer_with_input_shape tests/test_ops.py : :test_layer_wi... | pytest output results are garbled within pycharm |
Python | Loading an OpenFOAM case in ParaView using python is straight forward with : However , by default only the internalMesh mesh region is selected in the reader object.Using the trace method of ParaView is not of any help , since the MeshRegion property of the OpenFOAMReader object is simply set to the values of the mesh ... | ofReader = OpenFOAMReader ( FileName= ' < some OpenFOAM case directory > ' ) ofReader.MeshRegions = [ 'internalField ' , 'patch1 ' , 'patch2 ' ] | How to select all mesh regions in ParaView OpenFOAM case using python scripting ? |
Python | problem is very simple : I have two 2d np.array and I want to get a third array that only contains the rows that are not in common with the latter twos.for example : I tried np.delete ( X , Y , axis=0 ) but it does n't work ... | X = np.array ( [ [ 0,1 ] , [ 1,2 ] , [ 4,5 ] , [ 5,6 ] , [ 8,9 ] , [ 9,10 ] ] ) Y = np.array ( [ [ 5,6 ] , [ 9,10 ] ] ) Z = function ( X , Y ) Z = array ( [ [ 0 , 1 ] , [ 1 , 2 ] , [ 4 , 5 ] , [ 8 , 9 ] ] ) | Numpy : how delete rows common to 2 matrices |
Python | While answering this question I had a doubt regarding how to reduce multiple spaces in a string to one in Python without using regex . Say the string is as follows : The first solution that came to my mind was But this will not conserve leading and trailing spaces if the string was something likeIn order to conserve le... | s = `` Mary had a little lamb '' ' '.join ( s.split ( ) ) s = `` Mary had a little lamb `` ' '.join ( ( '- ' + s + '- ' ) .split ( ) ) [ 1 : -1 ] | Without regex reduce multiple spaces in a string to one in Python |
Python | I am trying to perform some simple mathematical operations on the files.The columns in below file_1.csv are dynamic in nature the number of columns will increased from time to time . So we can not have fixed last_column master_ids.csv : Before any pre-processingmaster_count.csv : Before any processingmaster_Ids.csv : a... | Ids , ref0 # the columns increase dynamically1234,10008435,52432341,5637352,345 Ids , Name , lat , lon , ref11234 , London,40.4,10.1,5008435 , Paris,50.5,20.2,4002341 , NewYork,60.6,30.3,7007352 , Japan,70.7,80.8,5001234 , Prague,40.4,10.1,1008435 , Berlin,50.5,20.2,2002341 , Austria,60.6,30.3,5007352 , China,70.7,80.8... | Pandas Column mathematical operations No error no answer |
Python | So , I was trying to make a basic Tic-Tac-Toe game with python , And I created one which works perfectly fine , but my code is not so good , as it has a lot of code for checking the list indexes ( Winner Of The Game ) , which kinda bothers me . So , How I avoid using the left index for checking the winner of the game ?... | board = [ ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' ] def show_board ( ) : # for showing the tic-tac-toe board print ( ' | ' + str ( board [ 0 ] ) + ' | ' + str ( board [ 1 ] ) + ' | ' + str ( board [ 2 ] ) + ' | ' ) print ( ' | ' + str ( board [ 3 ] ) + ' | ' + str ( board [ 4 ] ) + ' | ' + str ( board [ 5 ]... | How to avoid multiple ` elif ` statements ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.