text
stringlengths
46
37.3k
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 e...
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 ...
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 simpl...
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 ? <code> 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 posit...
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 : <code> def func ( ) : if 'assigned with equal ' : return 5 else : print 'not assigned ' func ( ) - > 'not assigned ' a =...
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...
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 . )...
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 ...
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...
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 th...
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 ...
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 fi...
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 ...
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 '...
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 ...
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 retu...
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...
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 <code> de...
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 ....
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 ! <code> cik0 cik1 cik2 'MKTG , INC. ' 0001019056 None None 1 800 FLOWERS COM INC 0001104659 0001437749 None 11 GOOD...
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...
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 ) : <code> 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_li...
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...
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 discon...
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 consu...
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 RE...
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 o...
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 ...
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 ...
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 ke...
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 al...
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 t...
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 ? <code> 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 ...
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 ... ? <code> s = 'SEQ ( A=1 % B=2 ) OPS ( CC=0 % G=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 : ] <code> my...
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 ? <code> class ...
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 ge...
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 ? <code> from sympy import *x = symbols ( `` x '' ) y = Function ( `` y '' ) dsolve ( diff ( y ( x ) , x ) - y ( x ) **x ) Eq ( y ( x ) , ( C1 - x* ( 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...
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...
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 : ) <code> # 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...
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...
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 : <code> a = [ 1,1,1,1 ] b = [ 2,...
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...
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 li...
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*~30...
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 ...
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 w...
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...
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 le...
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 , l...
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 tho...
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 : <code> $ python2Python 2.7.3 ( default , Nov 12 2012 , 09:50:25 ) [ GCC 4.2.1 Compatible Apple Clang 4.1 ( ( tags/Apple/clang...
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 the...
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 : <code> > > > from datetime import datetime , timezone > > > dt = datetime ( 20...
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 ...
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 ...
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 thi...
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 ...
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 ,...
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 expect...
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 : <code> day_list = [ `` Sunday '' , `` Monday '' , `` Tuesday '' , `` Wednesday '' , `` Thursday '' , `` Friday '' , `` Saturday '' ] def day_to_number ( inp ) : return [ day for day in range ( len ( day_lis...
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 ...
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 == ...
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 ? <code> def sayhi ( ui , repo , node , **opts ) : `` '' '' Says Hello '' ...
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 ? <code> 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 '' , lin...
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 ? <code> pd.DataFrame ( [ { 'col1 ' : 1 , 'col2 ' : 11 , 'col3 '...
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...
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 da...
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 hav...
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 pro...
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 ...
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 ...
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...
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...
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 ? <code> [ '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 vi...
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 . <code> 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 di...
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...
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...
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 rota...
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 co...
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 ...
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 allo...
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 ``...
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 'dic...
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...
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 <code> list_1 = [ np.NaN , np....
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...
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 ....
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 : <code> QString command = `` cd C : \\python\\python37 & & python C : \\projects\\file_editor.py...
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 ' : ...
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...
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...
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 ? <code> list = [ '247400015203223811 ' , 'DPF ' , '247400015203223813 ' , 'ZPF ' ] list2 = [ ] list = [ '24740001520322...
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 t...
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...
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 <code> > > > None > > > print ( repr ( None ) ) None > > >
'None ' is not displayed as I expected in Python interactive mode