lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I 'd like to know how I might be able to transform this problem to reduce the overhead of the np.sum ( ) function calls in my code.I have an input matrix , say of shape= ( 1000 , 36 ) . Each row represents a node in a graph . I have an operation that I am doing , which is iterating over each row and doing an element-wi... | nodes_nbrs = { 0 : [ 0 , 1 ] , 1 : [ 1 , 0 , 2 ] , 2 : [ 2 , 1 ] , ... } output = np.zeros ( shape=input.shape ) for k , v in nodes_nbrs.items ( ) : output [ k ] = np.sum ( input [ v ] , axis=0 ) | Code optimization - number of function calls in Python |
Python | I am trying to perform very simple computations on a huge file like counting the numbers of label for some columns or the average and standard deviation for other columns . The file is too big to fit in memory and I am currently processing it per line with : Now this seems to be too slow and I am wondering if it would ... | unique = { key : [ ] for key in categorical_keys } means = { key : 0.0 for key in numerical_keys } sds = { key : 0.0 for key in numerical_keys } with open ( 'input/train.csv ' , ' r ' ) as read_file : reader = csv.DictReader ( read_file , delimiter= ' , ' , quotechar='| ' ) for i , row in enumerate ( reader ) : for key... | python speed processing per line VS in chunk |
Python | Consider a set of numbers : Now I want to transform this set into another set y in the following way : for every element i in x , the corresponding element j in y would be the number of other elements in x which are less than i . For example , the above given x would look like : Now , I can do this using simple python ... | In [ 8 ] : import numpy as npIn [ 9 ] : x = np.array ( [ np.random.random ( ) for i in range ( 10 ) ] ) In [ 10 ] : xOut [ 10 ] : array ( [ 0.62594394 , 0.03255799 , 0.7768568 , 0.03050498 , 0.01951657 , 0.04767246 , 0.68038553 , 0.60036203 , 0.3617409 , 0.80294355 ] ) In [ 25 ] : yOut [ 25 ] : array ( [ 6. , 2. , 8. ,... | Transform a set of numbers in numpy so that each number gets converted into a number of other numbers which are less than it |
Python | I 'm trying to check for a vowel as the first character of a word . For my code I currently have this : I was wondering is there a much better way to do this check or is this the best and most efficient way ? | if first == ' a ' or first == ' e ' or first == ' i ' or first == ' o ' or first == ' u ' : | Is there a better way to check for vowels in the first position of a word ? |
Python | Recently I 've discovered Keras and TensorFlow and I 'm trying to get into ML . I have manually classified train and test data from my users DB like so:9 features and a label , the features are events in my system like `` user added a profile picture '' or `` user paid X for a service '' and the label is positive or ne... | import numpy as npfrom keras.layers import Densefrom keras.models import Sequentialtrain_data = np.loadtxt ( `` train.csv '' , delimiter= '' , '' , skiprows=1 ) test_data = np.loadtxt ( `` test.csv '' , delimiter= '' , '' , skiprows=1 ) X_train = train_data [ : , 0:9 ] Y_train = train_data [ : , 9 ] X_test = test_data ... | Get audiences insights using Keras and TensorFlow |
Python | Is there a way to know within a function if the function has been called by itself or assigned to a variable with = ? I would like to do something like this : that would give those outputs : | def func ( ) : if 'assigned with equal ' : return 5 else : print 'not assigned ' func ( ) - > 'not assigned ' a = func ( ) a- > 5 | Can a function know how it has been called ? |
Python | I 'm doing some experimentation with TensorFlow , and have run into a snag . I 'm trying to use TF to evalute a change in a model , then either retain or revert the model , based on the resultant change in loss function . I 've got the hard part ( conditional control ) figured out , but I 'm stuck on something that sho... | ... store_trainable_vars = [ ] for v in tf.trainable_variables ( ) : store_trainable_vars.append ( v ) ... def reject_move ( ) : revert_state = [ ] for ( v , s ) in zip ( tf.trainable_variables ( ) , store_trainable_vars ) : revert_state.append ( tf.assign ( v , s , name= '' revert_state '' ) ) return ( revert_state ) ... | How can I restore Tensors to a past value , without saving the value to disk ? |
Python | We have an ArrayList of items in several classes which are giving me trouble every time I 'd like to insert a new item into the list . It was a mistake on my part to have designed the classes in the way I did but changing the design now would be more headache than it 's worth ( bureaucratic waterfall model . ) I should... | Foo extends Bar { public Foo ( ) { m_Tags.add ( `` Jane '' ) ; m_Tags.add ( `` Bob '' ) ; m_Tags.add ( `` Jim '' ) ; } public String GetJane ( ) { return m_ParsedValue.get ( m_Tags.get ( 1 ) ) ; } public String GetBob ( ) { return m_ParsedValue.get ( m_Tags.get ( 2 ) ) ; } public String GetJim ( ) { return m_ParsedValu... | Reformatting code with Regular Expressions |
Python | I run a Random Forest algorithm with TF-IDF and non-TF-IDF features.In total the features are around 130k in number ( after a feature selection conducted on the TF-IDF features ) and the observations of the training set are around 120k in number.Around 500 of them are the non-TF-IDF features.The issue is that the accur... | drop_columns = [ 'labels ' , 'complete_text_1 ' , 'complete_text_2 ' ] # Split to predictors and targetsX_train = df.drop ( columns=drop_columns ) .valuesy_train = df [ 'labels ' ] .values # Instantiate , train and transform with tf-idf modelsvectorizer_1 = TfidfVectorizer ( analyzer= '' word '' , ngram_range= ( 1,2 ) ... | Accuracy with TF-IDF and non-TF-IDF features |
Python | Is there any possibility to write into generated view verbose informations about template generation in debug mode ? For example it could generate such output : base.html : page.html : Into such form : Why ? Because sometimes exploring some larger dependencies are very hard just by IDE . Or maybe you know some good too... | < html > < body > { % block content % } { % endblock % } < /body > < /html > { % extend `` base.html '' % } { % block content % } Foo { % include `` inner.html '' % } Bar { % endblock % } < html > < body > < ! -- block content -- > < ! -- from `` page.html '' -- > Foo < ! -- include `` inner.html '' -- > Bar < ! -- end... | Verbose mode in Django template tags |
Python | I tried the following code on Python , and this is what I got : It seems like for many changes I try to make to the iterables by changing elem , it does n't work . However if the iterables are objects with its own methods ( like a list ) , they can be modified in a for loop . In the for loop what exactly is the 'elem '... | lis = [ 1,2,3,4,5 ] for elem in lis : elem = 3print lis [ 1 , 2 , 3 , 4 , 5 ] lis = [ [ 1 ] , [ 2 ] ] for elem in lis : elem.append ( 8 ) print lis [ [ 1 , 8 ] , [ 2 , 8 ] ] | How does Python iterate a for loop ? |
Python | Say you have : My first question is : Is it worth having the try/finally ( or with ) statement ? Is n't the file closed anyway when the function terminates ( via garbage collection ) ? I came across this after reading a recipe form Martelli 's `` python cookbook '' wherecomes with the comment : `` When you do so , you ... | def my_func ( ) : fh = open ( ... ) try : print fh.read ( ) finally : fh.close ( ) all_the_text = open ( 'thefile.txt ' ) .read ( ) | Is it worth closing files in small functions ? |
Python | In computing the Chinese Remainder theorem from a vector of tuples ( residue , modulus ) the following code fails : Giving the result as 0 ( I guess the generated iterables are empty ) . Yet the following code works perfectly : Which yields ( a ) correct result of 8851.Why should I have to list ( one of the first gener... | c = ( ( 1,5 ) , ( 3,7 ) , ( 11,13 ) , ( 19,23 ) ) def crt ( c ) : residues , moduli = zip ( *c ) N = product ( moduli ) complements = ( N/ni for ni in moduli ) scaled_residues = ( product ( pair ) for pair in zip ( residues , complements ) ) inverses = ( modular_inverse ( *pair ) for pair in zip ( complements , moduli ... | Functional python -- why does only one of these generators require list ( ) to work ? |
Python | Aside : The title of this questions is not ideal . What I 'm trying to do could be achieved via computed types , but also by other means.I 'm writing some code that validates and sometimes converts JSON data , dynamically typed , to static Python types . Here are a few functions : These work great . I 'd also like to b... | def from_str ( x : Any ) - > str : assert isinstance ( x , str ) return xdef from_int ( x : Any ) - > int : assert isinstance ( x , int ) return xdef from_list ( f : Callable [ [ Any ] , T ] , x : Any ) - > List [ T ] : assert isinstance ( x , list ) return [ f ( y ) for y in x ] union = from_union ( [ from_str , from_... | Computed types in mypy |
Python | I answered a question here : comprehension list in python2 works fine but i get an error in python3OP 's error was using the same variables for max range and indices : This is a Python-3 error only , and related to the scopes that were added to the comprehension to avoid the variables defined here `` leaking '' . Chang... | x = 12y = 10z = 12n = 100ret_list = [ ( x , y , z ) for x in range ( x+1 ) for y in range ( y+1 ) for z in range ( z+1 ) if x+y+z ! =n ] UnboundLocalError : local variable ' y ' referenced before assignment > > ret_list = [ ( x , y , z ) for y in range ( y+1 ) for z in range ( z+1 ) if x+y+z ! =n ] UnboundLocalError : ... | Why does the UnboundLocalError occur on the second variable of the flat comprehension ? |
Python | The following is from the Python v3.1.2 documentation : From The Python Language Reference Section 3.3.1 Basic Customization : From The Glossary : This is true up through version 2.6.5 : But in version 3.1.2 : So which is it ? Should I report a documentation bug or a program bug ? And if it 's a documentation bug , and... | object.__hash__ ( self ) ... User-defined classes have __eq__ ( ) and __hash__ ( ) methods by default ; with them , all objects compare unequal ( exceptwith themselves ) and x.__hash__ ( ) returns id ( x ) . hashable ... Objects which are instances of user-defined classes are hashable by default ; they all compare uneq... | Contrary to Python 3.1 Docs , hash ( obj ) ! = id ( obj ) . So which is correct ? |
Python | Given a list of upperbounds : B1 , B2 , .. BN ; Dependency Functions : f1 , ... , fN-1 , I 'm wondering if there 's a recipe using itertools or other classes in python for : Where there are N levels of nesting ? I want to use this helper function like this : dependentProducts ( Bs , fs , dostuff ) , which returns a lis... | for i1 in range ( 0 , B1 ) : for i2 in range ( f1 ( i1 ) , B2 ) : ... for iN in range ( fN-1 ( iN-1 ) , BN ) dostuff ( i1 , i2 , ... iN ) | Using itertools for arbitrary number of nested loops of different ranges with dependencies ? |
Python | According to the documentation : Once an iterator ’ s __next__ ( ) method raises StopIteration , it must continue to do so on subsequent calls . Implementations that do not obey this property are deemed broken.However , for file-objects : Are file-object iterators broken ? Is this just one of those things that ca n't b... | > > > f = open ( 'test.txt ' ) > > > list ( f ) [ ' a\n ' , ' b\n ' , ' c\n ' , '\n ' ] > > > next ( f ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > StopIteration > > > f.seek ( 0 ) 0 > > > next ( f ) ' a\n ' | Is the File-Object iterator `` broken ? '' |
Python | I am trying to create a simple post sharing form like this one.I 'm using formset for image upload . But this gives me multiple input as you can see . Also each input can choose single image . But I 'm trying to upload multiple image with single input.views.pyshare.htmlif you need , forms.pymodels.py | def share ( request ) : ImageFormSet = modelformset_factory ( Images , form=ImageForm , extra=3 ) # 'extra ' means the number of photos that you can upload ^ if request.method == 'POST ' : postForm = PostForm ( request.POST ) formset = ImageFormSet ( request.POST , request.FILES , queryset=Images.objects.none ( ) ) if ... | Django formset creates multiple inputs for multiple image upload |
Python | In python Source code , the int object creation method PyInt_FromLong , python create a new PyIntObject at the position of free_list 's first element pointing to.Here is the code : and Py_TYPE is : How does free_list = ( PyIntObject * ) Py_TYPE ( v ) ; work ? It move free_list to point to next object in list . I think ... | PyObject *PyInt_FromLong ( long ival ) { register PyIntObject *v ; # if NSMALLNEGINTS + NSMALLPOSINTS > 0 if ( -NSMALLNEGINTS < = ival & & ival < NSMALLPOSINTS ) { v = small_ints [ ival + NSMALLNEGINTS ] ; Py_INCREF ( v ) ; return ( PyObject * ) v ; } # endif if ( free_list == NULL ) { if ( ( free_list = fill_free_list... | How does Python source code `` free_list = ( PyIntObject * ) Py_TYPE ( v ) ; '' move the pointer free_list to next object ? |
Python | I would like to merge 2 dataframes : df1 : df2 : Expected result : I would to match cik0 with df2 [ 'cik ' ] , if it does n't work , I would like to look at cik1 , and so on.Thanks for your help ! | cik0 cik1 cik2 'MKTG , INC. ' 0001019056 None None 1 800 FLOWERS COM INC 0001104659 0001437749 None 11 GOOD ENERGY INC 0000930413 None None 1347 CAPITAL CORP 0001144204 None None 1347 PROPERTY INSURANCE HOLDINGS , INC. 0001387131 None None cik Ticker0 0001144204 AABB1 0001019056 A2 0001387131 AABC3 0001437749 AA4 00009... | Merge on one column or another |
Python | I am trying to parse a large file , line by line , for relevant information.I may be receiving either an uncompressed or gzipped file ( I may have to edit for zip file at a later stage ) .I am using the following code but I feel that , because I am not inside the with statement , I am not parsing the file line by line ... | if `` .gz '' in FILE_LIST [ 'INPUT_FILE ' ] : with gzip.open ( FILE_LIST [ 'INPUT_FILE ' ] ) as input_file : file_content = input_file.readlines ( ) else : with open ( FILE_LIST [ 'INPUT_FILE ' ] ) as input_file : file_content = input_file.readlines ( ) for line in file_content : # do stuff | Parsing large , possibly compressed , files in Python |
Python | I have this piece of code in Python : Is there a more pythonic way of doing this ? Something like ( invalid python code follows ) : | if ' a ' in my_list and ' b ' in my_list and ' c ' in my_list : # do something print my_list if ( ' a ' , ' b ' , ' c ' ) individual_in my_list : # do something print my_list | Pythonic way of checking if several elements are in a list |
Python | I am new to python recently . Previously all my programming knowledge are limited on Java . So here I have a question about object variables in Python . I know that object variables in Python share on class instances . For example.So my questions is that how many memory copies does A.list have ? only 1 or just as many ... | class A : list= [ ] y=A ( ) x=A ( ) x.list.append ( 1 ) y.list.append ( 2 ) x.list.append ( 3 ) y.list.append ( 4 ) print x.list [ 1,2,3,4 ] print y.list [ 1,2,3,4 ] | How many memory copies do object variables in Python have ? |
Python | In networkx there is a function to plot a tree using a radial layout ( graphviz 's `` twopi '' ) : One can specify the root node with the argument root ( which is added to args under the hood as args += f '' -Groot= { root } '' ) .But how do you specify multiple roots when the graph consists of multiple disconnected co... | import pydotfrom networkx.drawing.nx_pydot import graphviz_layoutpos = graphviz_layout ( G , prog='twopi ' , root=root , args= '' ) | Networkx : how to specify multiple roots for plotting multiple trees at once ? |
Python | I would like to create a data structure that behaves like a dictionary with one added functionality which is to keep track of which keys have been `` consumed '' . Please note that I ca n't just pop the values as they are being reused.The structure should support these three cases , i.e . mark the key as consumed when ... | if key in d : ... d [ key ] d.get ( key ) class DictWithMemory ( dict ) : def __init__ ( self , *args , **kwargs ) : self.memory = set ( ) return super ( DictWithMemory , self ) .__init__ ( *args , **kwargs ) def __getitem__ ( self , key ) : self.memory.add ( key ) return super ( DictWithMemory , self ) .__getitem__ ( ... | Python dictionary with memory of keys that were accessed ? |
Python | I 'm using Python 2.7.6 . I ca n't understand the following result from re.findall : I expected the above to return [ ' 6 ' , ' 7 ' ] , because according to the documentation : '| ' A|B , where A and B can be arbitrary REs , creates a regular expression that will match either A or B . An arbitrary number of REs can be ... | > > > re.findall ( '\d|\ ( \d , \d\ ) ' , ' ( 6,7 ) ' ) [ ' ( 6,7 ) ' ] | Python regex findall alternation behavior |
Python | Assuming I want have a numpy array of size ( n , m ) where n is very large , but with a lot of duplication , ie . 0 : n1 are identical , n1 : n2 are identical etc . ( with n2 % n1 ! =0 , ie not regular intervals ) . Is there a way to store only one set of values for each of the duplicates while having a view of the ent... | unique_values = np.array ( [ [ 1,1,1 ] , [ 2,2,2 ] , [ 3,3,3 ] ] ) # these are the values i want to store in memoryindex_mapping = np.array ( [ 0,0,1,1,1,2,2 ] ) # a mapping between index of array above , with array belowunique_values_view = np.array ( [ [ 1,1,1 ] , [ 1,1,1 ] , [ 2,2,2 ] , [ 2,2,2 ] , [ 2,2,2 ] , [ 3,3... | broadcast views irregularly numpy |
Python | I have the following three python scripts : parent1.pyparent2.py : child.py : If i call parent1.py with : it gives me like expected the following output : if i call parent2.py with : i get the same output . But in the first example i get the output of child.py as bytes and in the second i get it directly as a string . ... | import subprocess , os , sysrelpath = os.path.dirname ( sys.argv [ 0 ] ) path = os.path.abspath ( relpath ) child = subprocess.Popen ( [ os.path.join ( path , 'child.lisp ' ) ] , stdout = subprocess.PIPE ) sys.stdin = child.stdoutinp = sys.stdin.read ( ) print ( inp.decode ( ) ) import sysinp = sys.stdinprint ( inp ) p... | The difference between bash and python pipes |
Python | I write a script to capture the independence date of few countries on Wikipedia.For example , with the Kazakhstan : And I have the following output : This output is not localised in the infobox but after , in the text . It 's because `` formation.find_next ( text = re.compile ( `` independence '' ) ) '' found something... | URL_QS = 'https : //en.wikipedia.org/wiki/Kazakhstan ' r = requests.get ( URL_QS ) soup = BeautifulSoup ( r.text , 'lxml ' ) # Only keep the infobox ( top right ) infobox = soup.find ( `` table '' , class_= '' infobox geography vcard '' ) if infobox : formation = infobox.find_next ( text = re.compile ( `` Formation '' ... | Python & Beautiful Soup : Searching only in a certain class |
Python | For my customers , iterating through multiple counters is turning into a recurring task.The most straightforward way would be something like this : The number of counters can be anywhere from 3 on up and those nested for loops start taking up real estate.Is there a Pythonic way to do something like this ? I keep thinki... | cntr1 = range ( 0,2 ) cntr2 = range ( 0,5 ) cntr3 = range ( 0,7 ) for li in cntr1 : for lj in cntr2 : for lk in cntr3 : print li , lj , lk for li , lj , lk in mysteryfunc ( cntr1 , cntr2 , cntr3 ) : print li , lj , lk | Python : Nesting counters |
Python | Situation : text : a stringR : a regex that matches part of the string . This might be expensive to calculate . I want to both delete the R-matches from the text , and see what they actually contain . Currently , I do this like : This runs the regex twice , near as I can tell . Is there a technique to do it all on pass... | import reab_re = re.compile ( `` [ ab ] '' ) text= '' abcdedfe falijbijie bbbb laifsjelifjl '' ab_re.findall ( text ) # [ ' a ' , ' b ' , ' a ' , ' b ' , ' b ' , ' b ' , ' b ' , ' b ' , ' a ' ] ab_re.sub ( `` , text ) # 'cdedfe flijijie lifsjelifjl ' | Capture the contents of a regex and delete them , efficiently |
Python | In Python 3 , I defined two paths using pathlib , say : How can I get the relative path that leads from origin to destination ? In this example , I 'd like a function that returns ../../osgiliath/tower or something equivalent.Ideally , I 'd have a function relative_path that always satisfies ( well , ideally there woul... | from pathlib import Pathorigin = Path ( 'middle-earth/gondor/minas-tirith/castle ' ) .resolve ( ) destination = Path ( 'middle-earth/gondor/osgiliath/tower ' ) .resolve ( ) origin.joinpath ( relative_path ( origin , destination ) ) .resolve ( ) == destination.resolve ( ) | How to get the relative path between two absolute paths in Python using pathlib ? |
Python | I am storing the above dataframe in a sqlite db as follows : However , I get an error when I try to read it back : The tmp.db is created , since I can see it in SQLite studio . What am I doing wrong ? | RUN YR AP15 PMTE RSPC NPPC NEE SSF PRK QDRN 0 1 2008 4.53 0.04 641.21 16.8 624.41 328.66 2114.51 0 1 1 2009 3.17 0.03 1428.30 0.0 1428.30 23.58 3.20 0 2 1 2010 6.20 0.03 1124.97 0.0 1124.97 23.94 18.45 0 3 1 2011 5.38 0.02 857.76 0.0 857.76 28.40 42.54 0 4 1 2012 7.32 0.02 831.42 0.0 831.42 23.92 25.58 0 from sqlalchem... | Error opening sqlite table using pandas |
Python | I want to make this string to be dictionary.FollowingI tried this codeBut an error occurredI know why this error occurred , the solution is deleting bracket of endBut it is not good for me . Any other good solution to make this string to be dictionary type ... ? | s = 'SEQ ( A=1 % B=2 ) OPS ( CC=0 % G=2 ) T1 ( R=N ) T2 ( R=Y ) ' { 'SEQ ' : ' A=1 % B=2 ' , 'OPS ' : 'CC=0 % G=2 ' , 'T1 ' : ' R=N ' , 'T2 ' : ' R=Y ' } d = dict ( item.split ( ' ( ' ) for item in s.split ( ' ) ' ) ) ValueError : dictionary update sequence element # 4 has length 1 ; 2 is required s = 'SEQ ( A=1 % B=2 ... | Splitting bracket-separated string to a dictionary |
Python | Is it possible to assign to a list slice in one go , that would achieve the following as : I know I can write it like this : but I was wondering if it is possible to this any other way . Or have been spoilt by Haskell 's pattern matching . something like x , xs = mylist [ : funky : slice : method : ] | mylist = [ 1,2,3,4,5,6,7 ] xs = mylist [ : -1 ] x = mylist [ -1 ] xs == [ 1,2,3,4,5,6 ] x == 7 xs , x = mylist [ : -1 ] , mylist [ -1 ] | assigning two variables to one list slice |
Python | In a code where there are different old-style classes like this one : and exceptions are raised this way : Is there a type to catch all those old-style class exceptions ? like this : Or at least is there a way to catch everything ( old- and new-style ) and get the exception object in a variable ? | class customException : pass raise customException ( ) try : ... except EXCEPTION_TYPE as e : # do something with e try : ... except : # this catches everything but there is no exception variable | How to catch all old-style class exceptions in python ? |
Python | I 'm trying to use the property decorator in a Class . While it works well per se , I ca n't use any code that has to access the REQUEST.Although calling get_someValue gets me the desired result , trying to access someValue raises an AttributeError.What 's the logic behind this behaviour ? Is there a way to get around ... | class SomeClass ( ) : # Zope magic code _properties= ( { 'id ' : 'someValue ' , 'type ' : 'ustring ' , 'mode ' : ' r ' } , ) def get_someValue ( self ) : return self.REQUEST @ property def someValue ( self ) : return self.REQUEST | Zope : can not access REQUEST under property decorator |
Python | Here 's what I did : The answer I get ( SymPy 1.0 ) is : But that 's wrong . Both Mathematica and Maple ca n't solve this ODE . What 's happening here ? | from sympy import *x = symbols ( `` x '' ) y = Function ( `` y '' ) dsolve ( diff ( y ( x ) , x ) - y ( x ) **x ) Eq ( y ( x ) , ( C1 - x* ( x - 1 ) ) ** ( 1/ ( -x + 1 ) ) ) | SymPy `` solves '' a differential equation it should n't solve |
Python | So I 'm using Python as a front end GUI that interacts with some C files for storage and memory management as a backend . Whenever the GUI 's window is closed or exited , I call all the destructor methods for my allocated variables.Is there anyway to check memory leaks or availability , like a C Valgrind check , right ... | from tkinter import *root = Tk ( ) # New GUI # some code heredef destructorMethods : myFunctions.destructorLinkedList ( ) # Destructor method of my allocated memory in my C file # Here is where I would want to run a Valgrind/Memory management check before closing root.destroy ( ) # close the programroot.protocol ( `` W... | Python : Ctypes how to check memory management |
Python | My question is similar to this , but instead of removing full duplicates I 'd like to remove consecutive partial `` duplicates '' from a list in python.For my particular use case , I want to remove words from a list that start consecutive with the same character , and I want to be able to define that character . For th... | [ ' # python ' , 'is ' , ' # great ' , 'for ' , 'handling ' , 'text ' , ' # python ' , ' # text ' , ' # nonsense ' , ' # morenonsense ' , ' . ' ] [ ' # python ' , 'is ' , ' # great ' , 'for ' , 'handling ' , 'text ' , ' . ' ] | Removing elements that have consecutive partial duplicates in Python |
Python | The output of this program isBut it should beBut if I doIt works perfectlyI want to know why , and how to solve this problemp.s . sorry if my english is bad : ) | # it 's python 3.2.3class point : def __init__ ( self , x , y ) : self.x = x self.y = y def __add__ ( self , point ) : self.x += point.x self.y += point.y return self def __repr__ ( self ) : return 'point ( % s , % s ) ' % ( self.x , self.y ) class Test : def __init__ ( self ) : self.test1 = [ point ( 0 , i ) for i in ... | Custom addition method fails during string interpolation |
Python | I 'm reading in a collection of objects ( tables like sqlite3 tables or dataframes ) from an Object Oriented DataBase , most of which are small enough that the Python garbage collector can handle without incident . However , when they get larger in size ( less than 10 MB 's ) the GC does n't seem to be able to keep up ... | walk = walkgenerator ( '/path ' ) objs = objgenerator ( walk ) with db.transaction ( bundle=True , maxSize=10000 , maxParts=10 ) : oldobj = None oldtable = None for obj in objs : currenttable = obj.table if oldtable and oldtable in currenttable : db.delete ( oldobj.path ) del oldtable oldtable = currenttable del oldobj... | Managing Memory with Python Reading Objects of Varying Sizes from OODB 's |
Python | I have arbitrary lists , for instance here are three lists : And I want transpose them together in order to get the output like this : As , you can see , I just converted `` columns '' to `` rows '' .The issue is a solution has to be independent of the lists length.For example : | a = [ 1,1,1,1 ] b = [ 2,2,2,2 ] c = [ 3,3,3,3 ] f_out = [ 1,2,3 ] g_out = [ 1,2,3 ] ... n_out = [ 1,2,3 ] a = [ 1,1 ] b = [ 2 ] c = [ 3,3,3 ] # outputf_out = [ 1,2,3 ] g_out = [ 1,3 ] n_out = [ 3 ] | Lists sorting in Python ( transpose ) |
Python | I 'm coming from Python , and trying to understand how lambda expressions work differently in Java . In Python , you can do stuff like : How can I accomplish something similar in Java ? I have read a bit on Java lambda expressions , and it seems I have to declare an interface first , and I 'm unclear about how and why ... | opdict = { `` + '' : lambda a , b : a+b , `` - '' : lambda a , b : a-b , `` * '' : lambda a , b : a*b , `` / '' : lambda a , b : a/b } sum = opdict [ `` + '' ] ( 5,4 ) Map < String , MathOperation > opMap = new HashMap < String , MathOperation > ( ) { { put ( `` + '' , ( a , b ) - > b+a ) ; put ( `` - '' , ( a , b ) - ... | How to map lambda expressions in Java |
Python | I am new to Python and had a question about updating a list using a for loop . Here is my code : I used the first for loop to check if the syntax was correct , and it worked fine . But the second for loop is the code I want to use , but it 's not working properly . How would I go about globally updating the list with t... | urls = [ 'http : //www.city-data.com/city/javascript : l ( `` Abbott '' ) ; ' , 'http : //www.city-data.com/city/javascript : l ( `` Abernathy '' ) ; ' , 'http : //www.city-data.com/city/Abilene-Texas.html ' , 'http : //www.city-data.com/city/javascript : l ( `` Abram-Perezville '' ) ; ' , 'http : //www.city-data.com/c... | Python List in a For Loop |
Python | I have an input matrix A of size I*JAnd an output matrix B of size N*MAnd some precalculated map of size N*M*2 that dictates for each coordinate in B , which coordinate in A to take . The map has no specific rule or linearity that I can use . Just a map that seems random.The matrices are pretty big ( ~5000*~3000 ) so c... | for i in range ( N ) : for j in range ( M ) : B [ i , j ] = A [ mapping [ i , j , 0 ] , mapping [ i , j , 1 ] ] B [ coords_y , coords_x ] = A [ some_mapping [ : , 0 ] , some_mapping [ : , 1 ] ] # Where coords_x , coords_y are defined as all of the coordinates : # [ [ 0,0 ] , [ 0,1 ] .. [ 0 , M-1 ] , [ 1,0 ] , [ 1,1 ] .... | numpy - efficiently copy values from matrix to matrix using some precalculated map |
Python | How can I uniquify the following list in Python : Desired output is : i.e . I need to get rid of tuples that have the same set of numbers but in different order.I tried but it only transpose elements.And when I dothe things getting only worse : In other words I need to convert inner tuple to a collection that allows mu... | all_the_ways = [ ( 5 , ) , ( 2 , 2 , 1 ) , ( 2 , 1 , 2 ) , ( 2 , 1 , 1 , 1 ) , ( 1 , 2 , 2 ) , \ ( 1 , 2 , 1 , 1 ) , ( 1 , 1 , 2 , 1 ) , ( 1 , 1 , 1 , 2 ) , ( 1 , 1 , 1 , 1 , 1 ) ] [ ( 5 , ) , ( 2 , 2 , 1 ) , ( 2 , 1 , 1 , 1 ) , ( 1 , 1 , 1 , 1 , 1 ) ] set ( all_the_ways ) list ( map ( set , all_the_ways ) ) [ { 5 } , ... | Get list of unique multi-sets |
Python | Suppose I have the following code : I want to calculate output only until output > a given number ( it can be assumed that elements of output decreases monotonically with increase of x ) and then stop ( NOT calculating for all values of x and then sorting , that 's inefficient for my purpose ) . Is there any way to do ... | from scipy import *import multiprocessing as mpnum_cores = mp.cpu_count ( ) from joblib import Parallel , delayedimport matplotlib.pyplot as pltdef func ( x , y ) : return y/xdef main ( y , xmin , xmax , dx ) : x = arange ( xmin , xmax , dx ) output = Parallel ( n_jobs=num_cores ) ( delayed ( func ) ( i , y ) for i in ... | How to implement parallel , delayed in such a way that the parallelized for loop stops when output goes below a threshold ? |
Python | I am looking into trying to create a full address , but the data I have comes in the form of : There are a few other permutations of how this data is created , but I want to be able to merge all this into one string where there is no overlap . So I want to create the string:1 , First Street , City , X13But not 1 , Firs... | Line 1 | Line 2 | Postcode1 , First Street , City , X131 , First Street First Street , City X13 1 1 , First Street , City , X13 X13 | Python - Merging two strings that overlap |
Python | I am currently trying to do the following : However Popen is complaining that \\1 is an invalid reference . Upon inspecting it in pdb I see this , It appears as though python is adding an extra \ . Is there any way to prevent that so that I can run the command as is using Popen ? Also , for simplification I left it out... | cmd = r'sudo sed -irn `` 1 ! N ; s/ < ip > 127.0.0.1 < \/ip > ( \n.*4000 . * ) / < ip > 0.0.0.0 < \/ip > \1/ '' /usr/something.conf'subprocess.Popen ( cmd ) 'sudo sed -irn `` 1 ! N ; s/ < ip > 127.0.0.1 < \\/ip > ( \\n.*4000 . * ) / < ip > 0.0.0.0 < \\/ip > \\1/ '' /usr/something.conf ' def _formatCmd ( cmdString , hos... | Doubled escape character |
Python | I have a module which I need to import and change particular variable values inside imported instance of that module and then execute it.Please note that I can not make a single change to the module being imported due to legacy reasons.Here is what I am trying to do : say the module i want to import , a.py , looks like... | var1 = 1var2 = 2if __name__ == '__main__ ' : print var1+var2 import runpyimport aa.var1 = 2result = runpy._run_module_as_main ( a.__name__ ) | How to import a module and change a variable value inside module and execute it |
Python | I am trying to make a list of groups that I extract from a list of lists.The main list I have contains lists which are of different lengths . I want to group up all the sub-lists that contain at least one value from another sub-list efficiently.For instance I want this : to be grouped up like thisThe way I thought of d... | [ [ 2 ] , [ 5 ] , [ 5,8,16 ] , [ 7,9,12 ] , [ 9,20 ] ] my_groups = { `` group1 '' : [ 2 ] , `` group2 '' : [ 5,8,16 ] , `` group3 '' : [ 7,9,12,20 ] } reduce ( np.intersect1d , ( SUPERLIST ) ) my_dict = dict ( ) unique_id = 0for sub_list_ref in super_list : sub_set_ref = set ( sub_list_ref ) for sub_list_comp in super_... | Make a numpy array of sets from a list of lists |
Python | Why can spaces sometimes be omitted before and after key words ? For example , why is the expression 2if-1e1else 1 valid ? Seems to work in both CPython 2.7 and 3.3 : and even in PyPy : | $ python2Python 2.7.3 ( default , Nov 12 2012 , 09:50:25 ) [ GCC 4.2.1 Compatible Apple Clang 4.1 ( ( tags/Apple/clang-421.11.66 ) ) ] on darwinType `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > 2if-1e1else 12 $ python3Python 3.3.0 ( default , Nov 12 2012 , 10:01:55 ) [ GCC 4... | Why does n't Python always require spaces around keywords ? |
Python | If I have a function such as sin ( 1/x ) I want to plot and show close to 0 , how would I smooth out the results in the plot ? The default number of sample points is relatively small for what I 'm trying to show . Here 's the code : As x approaches 0 , the line becomes more jagged and less `` curvy '' . Is there some w... | from sympy import symbols , plot , sinx = symbols ( ' x ' ) y = sin ( 1/x ) plot ( y , ( x , 0 , 0.5 ) ) | Smoothing sympy plots |
Python | This is the default string representation of a datetime : What is the correct format string to parse that with datetime.strptime ? That is , what format goes in place of the `` ? ? ? '' to consistently have the following invariant : | > > > from datetime import datetime , timezone > > > dt = datetime ( 2017 , 1 , 1 , tzinfo=timezone.utc ) > > > print ( dt ) 2017-01-01 00:00:00+00:00 > > > dt == datetime.strptime ( str ( dt ) , `` ? ? ? `` ) True | How to parse str ( my_datetime ) using strptime ? |
Python | I want to check whether a key exists in a dictionary . The most appropriate way , as per my knowledge is : if d_.get ( s ) : . But , while attempting a question on Leetcode , there was a TLE error when I was using this method . However , when I tried if s in d_ , TLE was gone . I want to know why in is faster than get ... | from typing import Listclass Solution : def __init__ ( self ) : self.word_dict = { } self.memo = { } def word_break ( self , s ) : if not s : return True if self.memo.get ( s ) : return self.memo [ s ] res = False for word in self.word_dict.keys ( ) : if len ( word ) < = len ( s ) and s [ : len ( word ) ] == word : res... | Why is key in dict ( ) faster than dict.get ( key ) in Python3 ? |
Python | Trying to explain the importance of semantic versioning to a friend , I faced the following dilemma.Let 's say we have library libfoo , version 1.2.3 that exposes the following function : Now assume that this function and its documentation change to : My first impression was to say that the next version would be 1.2.4 ... | def foo ( x , y ) : `` '' '' Compute the sum of the operands . : param x : The first argument . : param y : The second argument . : returns : The sum of ` x ` and ` y ` . `` '' '' return x + y def foo ( a , b ) : `` '' '' Compute the sum of the operands . : param a : The first argument . : param b : The second argument... | What does semantic versioning imply about parameter name changes ? |
Python | I am trying to speed up some code with multiprocessing in Python , but I can not understand one point . Assume I have the following dumb function : When I run this code without using multiprocessing ( see the code below ) on my laptop ( Intel - 8 cores cpu ) time taken is ~2.31 seconds.Instead , when I run this code by... | import timefrom multiprocessing.pool import Pooldef foo ( _ ) : for _ in range ( 100000000 ) : a = 3 t1 = time.time ( ) foo ( 1 ) print ( f '' Without multiprocessing { time.time ( ) - t1 } '' ) pool = Pool ( 8 ) t1 = time.time ( ) pool.map ( foo , range ( 8 ) ) print ( f '' Sample multiprocessing { time.time ( ) - t1 ... | Why is multiprocessing slower here ? |
Python | In Python 3.5+ , I often end up with a situation where I have many nested coroutines just in order to call something that 's deeply a coroutine , where the await merely comes in a tail call in most of the functions , like this : Those functions a , b , and c could be written as regular functions that return a coroutine... | import asyncioasync def deep ( time ) : await asyncio.sleep ( time ) return timeasync def c ( time ) : time *= 2 return await deep ( time ) async def b ( time ) : time *= 2 return await c ( time ) async def a ( time ) : time *= 2 return await b ( time ) async def test ( ) : print ( await a ( 0.1 ) ) loop = asyncio.get_... | Is it more Pythonic ( and/or performant ) to use or to avoid coroutines when making coroutine tail calls in Python ? |
Python | I came across something curious ( to me ) while trying to answer this question.Say I want to compare a series of shape ( 10 , ) to a df of shape ( 10,10 ) : yields , as expected , a matrix of the shape of the df ( 10,10 ) . The comparison seems to be row-wise.However consider this case : As far as I can tell , here Pan... | np.random.seed ( 0 ) my_ser = pd.Series ( np.random.randint ( 0 , 100 , size=10 ) ) my_df = pd.DataFrame ( np.random.randint ( 0 , 100 , size=100 ) .reshape ( 10,10 ) ) my_ser > 10 * my_df df = pd.DataFrame ( { 'cell1 ' : [ 0.006209 , 0.344955 , 0.004521 , 0 , 0.018931 , 0.439725 , 0.013195 , 0.009045 , 0 , 0.02614 , 0... | When does Pandas default to broadcasting Series and Dataframes ? |
Python | Note : The thread below prompted a pull request which was eventually merged into v1.10 . This issue is now resolved.I 'm using a subclassed DataFrame so that I can have more convenient access to some transformation methods and metadata particular to my use-case . Most of the DataFrame operations work as expected , in t... | class MyDataFrame ( pd.DataFrame ) : @ property def _constructor ( self ) : return MyDataFramedates = pd.date_range ( '2019 ' , freq= 'D ' , periods=365 ) my_df = MyDataFrame ( range ( len ( dates ) ) , index=dates ) assert isinstance ( my_df , MyDataFrame ) # Success ! assert isinstance ( my_df.diff ( ) , MyDataFrame ... | Pandas groupby , resample , etc for subclassed DataFrame |
Python | How do I remove the brackets from the result while keeping the function a single line of code ? Output : | day_list = [ `` Sunday '' , `` Monday '' , `` Tuesday '' , `` Wednesday '' , `` Thursday '' , `` Friday '' , `` Saturday '' ] def day_to_number ( inp ) : return [ day for day in range ( len ( day_list ) ) if day_list [ day ] == inp ] print day_to_number ( `` Sunday '' ) print day_to_number ( `` Monday '' ) print day_to... | My function returns a list with a single integer in it , how can I make it return only the integer ? |
Python | I need to know if in python exist a function or native lib that allow me to loop in a list more times than the number of elements in the list . In other words , when my index of interest is greater than the list size , the next element is the first of the list.For example , I have this list : So , if I have a parameter... | abc = [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' ] | How to loop in a list more times that list size in python ? |
Python | For the built-in python containers ( list , tuple , etc ) the in operator is equivalent to any ( y == item for item in container ) with the caveat that the former method is faster ( and prettier ) : Is there an equivalent to any ( y is item for item in container ) ? That is , a test that uses is instead of == ? | In [ 13 ] : container = range ( 10000 ) In [ 14 ] : % timeit ( -1 in container ) 1000 loops , best of 3 : 241 us per loopIn [ 15 ] : % timeit any ( -1 == item for item in container ) 1000 loops , best of 3 : 1.2 ms per loop | Do python lists have an equivalent for __contains__ that tests for identity ? |
Python | Say I want an extension that I can execute as follows : hg sayhiI tried the following , but it tells me there are invalid arguments : It seems no matter what I do , I need to give it an option like hg sayhi s. Is there anyway to do this ? | def sayhi ( ui , repo , node , **opts ) : `` '' '' Says Hello '' '' '' ui.write ( `` hi '' ) cmdtable = { `` sayhi '' : ( sayhi , [ ] , `` ) } | Mercurial Extension with no/default options |
Python | The output is If line 2 is neither line 3 nor line 4 , then what is it ? How does it get False ? | print ( ' a ' in 'aa ' ) print ( ' a ' in 'aa ' == True ) print ( ( ' a ' in 'aa ' ) == True ) print ( ' a ' in ( 'aa ' == True ) ) TrueFalseTrueTraceback ( most recent call last ) : File `` main.py '' , line 6 , in < module > print ( ' a ' in ( 'aa ' == True ) ) TypeError : argument of type 'bool ' is not iterable | Python `` in '' and `` == '' confusion |
Python | I 'm trying repeat the rows of a dataframe . Here 's my original data : which gives meI 'd like to repeat the rows depending on the length of the array in col3 i.e . I 'd like to get a dataframe like this one.What 's a good way accomplishing this ? | pd.DataFrame ( [ { 'col1 ' : 1 , 'col2 ' : 11 , 'col3 ' : [ 1 , 2 ] } , { 'col1 ' : 2 , 'col2 ' : 22 , 'col3 ' : [ 1 , 2 , 3 ] } , { 'col1 ' : 3 , 'col2 ' : 33 , 'col3 ' : [ 1 ] } , { 'col1 ' : 4 , 'col2 ' : 44 , 'col3 ' : [ 1 , 2 , 3 , 4 ] } , ] ) col1 col2 col30 1 11 [ 1 , 2 ] 1 2 22 [ 1 , 2 , 3 ] 2 3 33 [ 1 ] 3 4 44... | repeating the rows of a data frame |
Python | Coming from the C/C++ world and being a Python newb , I wrote this simple string function that takes an input string ( guaranteed to be ASCII ) and returns the last four characters . If there ’ s less than four characters , I want to fill the leading positions with the letter ‘ A ' . ( this was not an exercise , but a ... | def copyFourTrailingChars ( src_str ) : four_char_array = bytearray ( `` AAAA '' ) xfrPos = 4 for x in src_str [ : :-1 ] : xfrPos -= 1 four_char_array [ xfrPos ] = x if xfrPos == 0 : break return str ( four_char_array ) input_str = `` 7654321 '' print ( `` The output of { 0 } is { 1 } '' .format ( input_str , copyFourT... | How to make this simple string function `` pythonic '' |
Python | I have stock market data for a single security going back 20 years . The data is currently in an Pandas DataFrame , in the following format : The problem is , I do not want any `` after hours '' trading data in my DataFrame . The market in question is open from 9:30AM to 4PM ( 09:30 to 16:00 on each trading day ) . I w... | mask = ( df [ 'date ' ] > '2015-07-06 09:30:0 ' ) & ( df [ 'date ' ] < = '2015-07-06 16:00:0 ' ) sub = df.loc [ mask ] | Pandas Dataframe - Droping Certain Hours of the Day from 20 Years of Historical Data |
Python | Sometimes I have to check for some condition that does n't change inside a loop , this means that the test is evaluated in every iteration , but I think this is n't the right way.I thought since the condition does n't change inside the loop I should only test it only once outside the loop , but then I will have to `` r... | # ! /usr/bin/pythonx = True # this wo n't be modified inside the loopn = 10000000def inside ( ) : for a in xrange ( n ) : if x : # test is evaluated n times pass else : pass def outside ( ) : if x : # test is evaluated only once for a in xrange ( n ) : pass else : for a in xrange ( n ) : passif __name__ == '__main__ ' ... | Testing a condition that does n't change inside a loop |
Python | The iter function wraps objects like lists or tuples in order to use them as iterators , i.e . one is able to use next , for example . For instance , returns 1.What happens internally if the object we pass to iter is already an iterator ? Does it simply return the original object , i.e . no-op ? Or does it produce a ne... | next ( iter ( [ 1 , 2 , 3 ] ) ) | Using iter on an existing iterator in Python : What happens to the iterator ? |
Python | The fact that Python is written in C and is actually a C program made me wonder about how decimal numbers assignment are handled.How does a C program implement the Python variable assignment of a very large decimal number ( bigger than int or long ) ? For example : when running in python I know that the value is so big... | a=10000 ... # a= ( 10^1000 ) | How does C implements the Python assignment of large numbers |
Python | I have a list of tuples as shown : I want to make the numbers keys of a dictionary and have them point to a list . That list then holds all associations in the list of tuples . So in the list above , it would split into a dictionary as : Currently I use the dictionary 's flexibility in automatically declaring new keys ... | lt = [ ( 1 , ' a ' ) , ( 1 , ' b ' ) , ( 2 , ' a ' ) , ( 3 , ' b ' ) , ( 3 , ' c ' ) ] dict_lt : { 1 : [ a , b ] ,2 : [ a ] ,3 : [ b , c ] } dict_lt = { } for tup in lt : dict_lt [ tup [ 0 ] ] = [ ] for tup in lt : dict_lt [ tup [ 0 ] ] .append ( tup [ 1 ] ) | Python , list of tuples split into dictionaries |
Python | I have a service running on a Linux box that creates a named pipe character device-special file , and I want to write a Python3 program that communicates with the service by writing text commands and reading text replies from the pipe device . I do n't have source code for the service.I can use os.open ( named_pipe_pat... | io.UnsupportedOperation : File or stream is not seekable . | How to open < del > named pipe < /del > character device special file for reading and writing in Python |
Python | I 've trained a Wide and Deep Model using Tensorflow 1.8.0 . My test and training dataset are separate files which were split previously . I 'm using tf.set_random_seed ( 1234 ) before tf.contrib.learn.DNNLinearCombinedClassifier as follows - It shows the following logs-From the log , I can see that the random seed was... | tf.set_random_seed ( 1234 ) import tempfilemodel_dir = tempfile.mkdtemp ( ) m = tf.contrib.learn.DNNLinearCombinedClassifier ( model_dir=model_dir , linear_feature_columns=wide_columns , dnn_feature_columns=deep_columns , dnn_hidden_units= [ 100 , 50 ] ) INFO : tensorflow : Using default config.INFO : tensorflow : Usin... | Tensorflow 1.8.0 : Wide and Deep Model results are not stable . Random seed is not working |
Python | I have a list of durations like belowwhere d stands for days , h stands for hours and m stands for minutes.I want to get the highest duration from this list ( 14d in this case ) . How can I get that from this list of strings ? | [ '5d ' , '20h ' , '1h ' , '7m ' , '14d ' , '1m ' ] | Get highest duration from a list of strings |
Python | I 've poured over the site for a while now , and have n't found a resolution that works for me . Long time listener , first time caller.I have an existing Django application ( based on the Django documentation sample site including 'polls ' ) . I 've moved this over and got it up and running on a web server via wsgi.I ... | INSTALLED_APPS = { 'django.contrib.admin ' , 'django.contrib.auth ' , 'django.contrib.contenttypes ' , 'django.contrib.sessions ' , 'django.contrib.messages ' , 'django.contrib.staticfiles ' , 'polls ' , 'core ' } from django.conf.urls import patterns , include , urlfrom django.contrib import adminurlpatterns = pattern... | Adding an application to hosted Django project |
Python | I want to be able to pass arguments like this : I saw this behavior in DjangoORM and SQLAlchemy but I do n't know how to achieve it . | fn ( a > =b ) or fn ( a ! =b ) | Pass ! , ! = , ~ , < , > as parameters |
Python | A module holds a dictionary to keep track of itscontext , such as the names defined at some point of the execution . This dictionary can be accessed through vars ( module ) ( or module.__dict__ ) if module was imported , or by a call to the locals built-in function in the module itself : Update and return a dictionary ... | def list_locals ( ) : print ( locals ( ) ) list_locals ( ) print ( locals ( ) ) | When is the locals dictionary set ? |
Python | In pandas , time series can be indexed by passing a string that is interpretable as a date . This works for a DataFrame too : I am looking for ways to do this when the timestamps are the column names.This yields TypeError : only integer scalar arrays can be converted to a scalar index . The same is true forThe most imm... | > > > dates = pd.date_range ( '2000-01-01 ' , periods=8 , freq='M ' ) > > > df = pd.DataFrame ( np.random.randn ( 8 , 4 ) , index=dates , columns= [ ' A ' , ' B ' , ' C ' , 'D ' ] ) > > > df A B C D2000-01-31 0.096115 0.069723 -1.546733 -1.6611782000-02-29 0.256296 1.838310 0.227132 1.7652692000-03-31 0.315862 0.167007... | How to select dataframe columns using string keys when the column names are timestamps ? |
Python | I 've got a list [ ' a ' , ' b ' , ' c ' , 'd ' ] and I need a list [ ' a ' , 'ab ' , 'abc ' , 'abcd ' , ' b ' , 'bc ' , 'bcd ' , ' c ' , 'cd ' , 'd ' ] .I 've been looking at itertools , but I 'm not seeing how to make this work.For all combinations , the code would be : What would I need to do to return only sequenti... | from itertools import permutationsstuff = [ ' a ' , ' b ' , ' c ' , 'd ' ] for i in range ( 0 , len ( stuff ) +1 ) : for subset in permutations ( stuff , i ) : print ( subset ) | How to create a sequential combined list in python ? |
Python | I was wondering how I could make a car that moves and rotates using the arrow keys . I am trying to make a car physics game where the player controls the car and drives around and parks , but I am having trouble with how to start implementing the controls . How could I make my car move the direction it 's rotating with... | import pygamepygame.init ( ) window = pygame.display.set_mode ( ( 800,800 ) ) pygame.display.set_caption ( `` car game '' ) class car : def __init__ ( self , x , y , height , width , color ) : self.x = x self.y = y self.height = height self.width = width self.color = color self.carimage = pygame.image.load ( `` 1.png '... | How Could I Make A Basic Car Physics In Pygame ? |
Python | As currently being discussed in this question , I am writing inclusive versions of the built-in range and xrange functions . If these are placed within a module named inclusive , I see two possible ways to name the functions themselves : Name the functions inclusive_range and inclusive_xrange so that client code can us... | from inclusive import * ... inclusive_range ( ... ) import inclusive ... inclusive.range ( ... ) | Is it OK to re-use the names of Python 's built-in functions ? |
Python | There appears to be a difference between how python 2.7.15 and 3.7.2 perform the lowercase operation.I have a large dictionary and a large list which were written using python 2 , but which I want to use in python 3 ( imported from file using pickle ) . For each item in the list of strings , there is a key in the dict ... | > > > u '' \u0130le '' .lower ( ) == `` ile '' > > > True > > > u '' \u0130le '' .lower ( ) == `` ile '' > > > False | How to simulate python 2 str.lower ( ) in python 3 |
Python | I am working on a project where I need to breakdown an integer value according to an array of percentage values . My end array must contain integer value and the sum of the array must be equal to the initial integer.Below is a fake example . We have a list of cars with some `` potentials '' and we need to allocate this... | from pyomo.environ import *from pprint import pprintdef distribute ( total , weights ) : scale = float ( sum ( weights.values ( ) ) ) / total return { k : v / scale for k , v in weights.items ( ) } Cars = [ `` car 1 '' , `` car 2 '' , `` car 3 '' ] Locations = [ `` p_code_1 '' , `` p_code_2 '' , `` p_code_3 '' ] POTENT... | Breakdown an integer value to an array of integer maintaining the sum |
Python | Well simply making a class iterable is easy enough using meta classes ( so some other answers here ) . However I wish to make a class iterable , and also enabling one to `` iterate a subgroup based on inheritance '' . An example of my use : The first loop works - it iterates over all instances and childs of `` A '' . H... | class IterPartRegistry ( type ) : def __iter__ ( cls ) : return iter ( cls._registry ) class A ( object , metaclass=IterPartRegistry ) : _registry = [ ] def __init__ ( self , name ) : self.name = name self._registry.append ( self ) class B ( A ) : passclass C ( A ) : passA ( `` A - first '' ) B ( `` B - first '' ) B ( ... | Make class iterable respecting inheritance |
Python | I have a simple test.py file where I want to add types using Cython . To stay python interpreter compatible , I use the pure python mode . I added : And then try to define a type by : Then the python interpreter in Eclipse gives me an error on this line : AttributeError : 'module ' object has no attribute 'dict'What di... | import cython d = cython.declare ( cython.dict ) | Cython pure python mode |
Python | I 've been working in a project that manages big lists of words and pass them trough a lot of tests to validate or not each word of the list . The funny thing is that each time that I 've used `` faster '' tools like the itertools module , they seem to be slower.Finally I decided to ask the question because it is possi... | # ! /usr/bin/python3 # import timefrom unicodedata import normalizefile_path='./tests'start=time.time ( ) with open ( file_path , encoding='utf-8 ' , mode='rt ' ) as f : tests_list=f.read ( ) print ( 'File reading done in { } seconds'.format ( time.time ( ) - start ) ) start=time.time ( ) tests_list= [ line.strip ( ) f... | why is `` any ( ) '' running slower than using loops ? |
Python | I have a list like this : So there are intervals that begin with 1 and end with 0.How can I replace the values in those intervals , say with 1 ? The outcome will look like this : I use NaN in this example , but a generalized solution that can apply to any value will also be great | list_1 = [ np.NaN , np.NaN , 1 , np.NaN , np.NaN , np.NaN , 0 , np.NaN , 1 , np.NaN , 0 , 1 , np.NaN , 0 , np.NaN , 1 , np.NaN ] list_2 = [ np.NaN , np.NaN , 1 , 1 , 1 , 1 , 0 , np.NaN , 1 , 1 , 0 , 1 , 1 , 0 , np.NaN , 1 , np.NaN ] | How to fill elements between intervals of a list |
Python | I recently had the following problem : I 'm developing a numerical library in Python ( called spuq ) that needs scipy at its core . Now one of the functions in scipy , its called btdtri , had a bug for a certain tuple of input parameters . This bug , however , is now fixed in scipy version 0.9 according to the develope... | import scipydef foo ( a , b , c ) : if scipy.__version__ > = ( 0 , 9 ) : return btdtri ( a , b , c ) else : return my_fixed_btdtri ( a , b , c ) from scipy import *if __version__ < ( 0 , 9 ) : btdtri = my_fixed_btdtri | Workaround for bugs in Python packages |
Python | Is there any existing implementation of Python2 where ordering is transitive ? That is , where it 's impossible to see this behaviour without creating user-defined types : CPython is not transitive because of this counterexampleHowever , this ordering in CPython is documented as only an implementation detail . | > > > x < y < z < xTrue x = ' b ' y = ( ) z = u'ab ' | Is there any implementation of Python2 where ordering is transitive ? |
Python | When I try to call python in c++ using this : I get this error : Any ideas how to fix this ? edit : My python related path in PATH variable is : and i can use Qtand i tried this as well : but then i get this error : | QString command = `` cd C : \\python\\python37 & & python C : \\projects\\file_editor.py '' QByteArray ba = command.toLocal8Bit ( ) ; const char *c_str2 = ba.data ( ) ; std : :system ( c_str2 ) Fatal Python error : initfsencoding : unable to load the file system codecModuleNotFoundError : No module named 'encodings ' C... | Error while calling python via std : :system |
Python | How do I convert a pandas dataFrame into a sparse dictionary of dictionaries , where only the indexes of some cutoff are shown . In the toy example below , I only want indexes for each column whose values > 0This gives : dfasdict = { 'cell_1 ' : { 'gene_a ' : -1 , 'gene_b ' : 0 , 'gene_c ' : 0 } , 'cell_2 ' : { 'gene_a... | import pandas as pdtable1 = [ [ 'gene_a ' , -1 , 1 ] , [ 'gene_b ' , 1 , 1 ] , [ 'gene_c ' , 0 , -1 ] ] df1 = pd.DataFrame ( table ) df1.columns = [ 'gene ' , 'cell_1 ' , 'cell_2 ' ] df1 = df1.set_index ( 'gene ' ) dfasdict = df1.to_dict ( orient='dict ' ) | Pandas dataframe into sparse dictionary of dictionaries |
Python | Using Python.So basically I have a XML like tag syntax but the tags do n't have attributes . So < a > but not < a value='t ' > . They close regularly with < /a > .Here is my question . I have something that looks like this : And I want to transform it into : I 'm not really looking for a completed solution but rather a... | < al > 1 . test2 . test2 test with new line3 . test3 < al > 1. test 4 < al > 2. test 5 3. test 6 4. test 7 < /al > < /al > 4 . test 8 < /al > < al > < li > test < /li > < li > test2 < /li > < li > test with new line < /li > < li > test3 < al > < li > test 4 < /li > < al > < li > test 5 < /li > < li > test 6 < /li > < l... | Best way transform custom XML like syntax |
Python | I am looking for a more efficient and maintainable way to offset values conditionally by group . Easiest to show an example.Value is always non-negative for Offset == False and always negative for Offset == True . What I 'm looking to do is `` collapse '' positive Values ( flooring at 0 ) against negative ones by Label... | df = pd.DataFrame ( { 'Label ' : [ 'L1 ' , 'L2 ' , 'L3 ' , 'L3 ' ] , 'Offset ' : [ False , False , False , True ] , 'Value ' : [ 100 , 100 , 50 , -100 ] } ) # input # Label Offset Value # 0 L1 False 100 # 1 L2 False 100 # 2 L3 False 50 # 3 L3 True -100 Label Offset Value0 L1 False 1001 L2 False 1002 L3 False 03 L3 True... | Conditionally offseting values by group with Pandas |
Python | I have a list aI want to get a list of strings like [ `` 247400015203223811 , DPF '' , `` 247400015203223813 , ZPF '' ] combining every 2 strings to 1 stringI tried likeis this even possible ? | list = [ '247400015203223811 ' , 'DPF ' , '247400015203223813 ' , 'ZPF ' ] list2 = [ ] list = [ '247400015203223811 ' , 'DPF ' , '247400015203223813 ' , 'ZPF ' ] for i in range ( 0 , len ( list ) , 2 ) : list2.append ( list [ i ] + list [ i ] ) | Combining every 2 string to 1 string |
Python | I 'm trying to print to console before and after processing that takes a while in a Django management command , like this : In the above code , Saving routes ... is expected to print before the loop begins , and done . right next to it when the loop completes so that it looks like Saving routes ... done . in the end.Ho... | import requestsimport xmltodictfrom django.core.management.base import BaseCommanddef get_all_routes ( ) : url = 'http : //busopen.jeju.go.kr/OpenAPI/service/bis/Bus ' r = requests.get ( url ) data = xmltodict.parse ( r.content ) return data [ 'response ' ] [ 'body ' ] [ 'items ' ] [ 'item ' ] class Command ( BaseComma... | Django management command does n't flush stdout |
Python | I am learning Python and came across an example that I do n't quite understand . In the official tutorial , the following code is given : Coming from c++ , it makes sense intuitively for me that this will print 5 . But I 'd also like to understand the technical explanation : `` The default values are evaluated at the p... | i = 5def f ( arg=i ) : print ( arg ) i = 6f ( ) | Scope for default parameter in Python |
Python | I thought the display in Python interactive mode was always equivalent to print ( repr ( ) ) , but this is not so for None . Is this a language feature or am I missing something ? Thank you | > > > None > > > print ( repr ( None ) ) None > > > | 'None ' is not displayed as I expected in Python interactive mode |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.