text
stringlengths
46
37.3k
title
stringlengths
12
162
Python : Say I want to debug a simple class with an attribute myattribute . I create a repr method like this : It feels a bit redundant , so I would prefer to use format directly : ... but that fails with an IndexError : tuple index out of range . I understand it that format can not access the self argument , but I do ...
How can I use ` str.format ` directly as ` __repr__ ` ?
Python : I have following DataFrame : I want to transform following Dataframe : into dataframe of rows : The products are known ahead.Any idea how to do so ? <code> data = { 'year ' : [ 2010 , 2010 , 2011 , 2012 , 2011 , 2012 , 2010 , 2011 , 2012 , 2013 ] , 'store_number ' : [ '1944 ' , '1945 ' , '1946 ' , '1947 ' , '1...
Transforming Dataframe columns into Dataframe of rows
Python : If I try to print the class variable which is a list , I get a Python object . ( These are examples I found on stackoverflow ) .But in this more simple example , it actually prints : I figured this line is the culprit : Contact.all_contacts.append ( self ) in the first sample code . But I 'm not exactly sure w...
How do I print this class variable ?
Python : Suppose you find yourself in the unfortunate position of having a dependency on a poorly behaved library . Your code needs to call FlakyClient.call ( ) , but sometimes that function ends up hanging for an unacceptable amount of time.As shown below , one way around this is to wrap the call in its own Process , ...
How can you safeguard yourself from a flaky library call that might hang indefinitely ?
Python : Is there a better way to do this ? I feel like I am doing something wrong by being too repetitive . <code> O = viz.pick ( 1 , viz.WORLD ) BackSetts = [ `` set_b1b '' , `` set_b2a '' , `` set_b1a '' , `` set_b2b '' ] LeftSetts = [ `` set_l1a '' , `` set_l1b '' , `` set_l2a '' , `` set_l1b '' ] NormSetts = [ `` ...
Is there a better way to write this ?
Python : I want to split array into array with mask and indexlike below into can I do this without loop ? Edit : More examples ... Say , we have an array a with shape [ 10 , 10 , 10 ] where a [ x , y , : ] = [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] Now given the mask b = [ 0 , 3 , 7 ] I want the output to be an array ...
can I split numpy array with mask ?
Python : Thanks in advance for helping.I have a csv file with the following structure : I need a nested JSON for use in D3 or amcharts . With the python script on this page ( https : //github.com/hettmett/csv_to_json ) I could create a nested JSON . The results looks like this : However it is not exactly what I need . ...
Problem creating nested JSON with python from csv with columns without value
Python : I 'm learning a bit of python coding and I 'm following this youtube video too to make some practice.Now here is what I 'm running.The strange thing is that for a few buses , the program somehow mixes longitude , latitude and direction for no apparent reason.For example , this is what I 've got right now : I k...
Ca n't spot a bug in my python code
Python : I came across a strange result while playing around with Pandas and I am not sure why this would work like this . Wondering if it is a bug.This gives `` 15.0 '' as result.This gives as result a Series : type ( df1.loc [ ' b ' , 'mvl ' ] ) - > pandas.core.series.Seriestype ( df.loc [ ' b ' , 'mvl ' ] ) - > nump...
Pandas - Category variable and group by - is this a bug ?
Python : If I write : I get : Why is it coercing them into ints ? It does the same thing in reverse.Output is : Can this be disabled ? Is it a bug ? <code> d = { 0 : ' a ' , 1 : ' b ' } d [ False ] = ' c 'd [ True ] = 'd'print ( d ) { 0 : ' c ' , 1 : 'd ' } d = { False : ' a ' , True : ' b ' } d [ 0 ] = ' c 'd [ 1 ] = ...
Dictionary coercion intentional or no ?
Python : I 've read various `` there is no truly private data in Python instances '' posts , but we 're all aware of using closures in Perl and JavaScript to effectively achieve private data . So why not in Python ? For example : Now we do : What can you do to the instance thing to get read access to the original strin...
Python private instance data revisited
Python : When inputting 1000 for the range of this code , many ellipse shapes are created , some of which are hard to see . This seems to only happen with the Fibonacci sequence and no other chains of long numbers . Why is this ? <code> in_range = int ( input ( `` range : `` ) ) fibo_list = [ ] a = 0b = 1count = 0if in...
Why do very large Fibonacci numbers create an ellipse-type shape ?
Python : so far my dataframe looks like this : I would like to replace the area ' Q ' with ' P ' for every row where the Stage is equal to ' X'.So the result should look like : I tried : It does not work . Help is appreciated ! : ) <code> ID Area Stage1 P X2 Q X3 P X4 Q Y ID Area Stage1 P X2 P X3 P X4 Q Y data.query ( ...
Replace column value based on value in other column
Python : I have two dataframes with the same columns : Dataframe 1 : Dataframe 2 : I want to generate a correlation and p-value dataframe of all posible combinations , this would be the result : The problem is that the cartesian product generates more than 3 million tuples . Taking minutes to finish . This is my code ,...
Optimizing cartesian product between two Pandas Dataframe
Python : Somewhat of a python/programming newbie here ... I am trying to come up with a regex that can handle extracting sentences from a line in a text file , and then appending them to a list . The code : Printed Output as per last 5 lines of above code : The contents of 'sample.txt ' : I have been playing around wit...
Python : Extracting Sentences From Line - Regex Needed Based on Criteria
Python : I am trying to match strings in a column of a data frame with the strings in a column of another data frame and map the corresponding values . The number of rows are different for both data framesExpected output <code> df1 = data.frame ( name = c ( `` ( CKMB ) Creatinine Kinase Muscle & Brain '' , `` 24 Hours ...
Matching strings in a column of a data frame with the strings in a column of another data frame using R or Python
Python : I am a newbie to JavaScript , but I am familiar with Python . I am trying to figure out the differences between the Dictionary in Python and the Object in JS.As far as I know , the key in a dictionary in Python needs to be defined in advance , but it could be undefined in an object in JS . However , I am confu...
I am so confused about Object in JavaScript
Python : This is homework , so I do n't expect the answer , just a point in the right direction.In python I have a dictionary that is like so : For example 'Racing Bike ' is the product name and the list of pairs is ( part , amount required ) , respectively.I have to write a function that , given the above dictionary a...
Finding an element of a list when the list is in a dictionary ?
Python : So I have a line of code : That throws me this error : But magically fixes itself if I take out the `` input '' : Here is the function specification in the PyTorch docs : https : //pytorch.org/docs/stable/_modules/torch/nn/utils/rnn.html # pack_padded_sequenceI 'm using Python3 and PyTorch 0.4 . Am I missing s...
Is `` input '' a keyword that causes errors when used as a parameter name ( in PyTorch ) ?
Python : This is n't a practical problem - I 'm just curious about some strange behavior I 've observed , and wondering if I understand the `` is '' operator correctly.Here 's some predictable Python interpreter output : Now let 's define a variable called True : The interpreter will still return `` True '' for boolean...
Strange behavior when defining a value for True in Python
Python : for some reason , any mouse event that happens with my program does n't make the image in the window disappear nor reappear , although my on_key_press ( ) function works.I 've tried state flags and declaring a new image resource , but it does n't change anything in the window.Is there a way to make this work ?...
Python Pyglet mouse events do n't call on_draw ( ) nor make changes in window
Python : I am writing code to read data from a CSV file to a pandas dataframe and to get the unique values and concatenate them as a string . The problem is that one of the columns contains the values True and False . So while concatenating the values I am getting the errorI want python to treat True as string rather t...
String Join treats True as Boolean rather than string
Python : I think I 'm overlooking something simple , but I ca n't seem to figure out what exactly . Please consider the following code : I expected that both for-loops would produce the same result , so 4 5 . However , the for-loop that prints the generator exp prints 4 5 6 7 8 9 . I think it has something to do with t...
Unexpected results when comparing list comprehension with generator expression
Python : I was just trying to learn K-ary tree implementation in Python and came across this link : http : //www.quesucede.com/page/show/id/python-3-tree-implementationIn the tree.py file , there is a section of code like this : What is self [ identifier ] ? Is it a list ? This is really confusing.Can someone explain a...
What does self [ identifier ] = some_value do in this code ?
Python : I have a question about this on testing the following code:1,2 , The file object closed when the file_close_test exits because no reference to it.After the exception raised , the file object not closed.so i think the related stack data not released.After exception_wrapper exit , the file closed automatically.c...
when to release function stack data in python ?
Python : This is actually in a job posting on SO and being a newbie I thought it was interesting . So you get output like the following : To me this is already confusing because I thought izip_longest ( * ( [ iter ( iterable ) ] * n ) ) would run the izip_longest function on a list of n identical iterators so I would h...
What does this function do ? ( Python iterators )
Python : I have two images , an analysis image and an ROI Mask image ( the ROI Mask image is below ) .What I want to do is to measure the RGB mean value in an area of the analysis image selected by the ROI Mask image . I am doing this by using a for loop but it takes too long.Is there any way to make this simpler ? <co...
How do I measure RGB mean in a unique ROI ?
Python : For some reason , I need to be able to delete all the children ( in some sense ) that were originated by some method of the class . Here is an example : What I want is somehow to append generated class B from gen_b to A ( ) .children so that : Additionally , I need this for cython ( I use cdef classes ) , so m...
Delete all variables ( classes ) generated by class method python
Python : Consider the following operation in the limit of low length iterables , Setting as a list is 25 % faster than using a generator expression ? Why is this the case as setting as a list is an extra operation.Note : In both runs I obtained the warning : The slowest run took 6.42 times longer than the fastest . Thi...
Is it faster to iterate a small list within an any ( ) statement ?
Python : I am having a dataset with dates and company names . I only want to keep rows such that the combination of the company name and the date appeared in the dataset at least twice . To illustrate the problem , let us assume I have the following dataframe : My desired output would be : I would know how to drop the ...
Drop rows in pandas if records in two columns do not appear together at least twice in the dataset
Python : I am working on a project where very specific scheduling is needed ( and why I am not using a library ) . It works , but I am trying to find a faster solution to the following problem : We have employees requesting hours every week . They input their total availability for the week ( ex : 8-1 M , W , R ) . The...
How to efficiently and quickly find valid combinations out of an array of string elements for employee scheduling ?
Python : I wrote a simple prime sieve ( an unbounded sieve of Eratosthenes ) using Python , but for some reason , it is n't working correctly . Here is the sieve : Unfortunately , this is n't working . Instead , it just returns the same values as the count ( 2 ) iterator would.For comparison , this : will print : while...
Creating a simple prime sieve in Python
Python : Ok , this might be a very stupid question and it might not be possible , or I am thinking in a twisted way . So , consider this : Ok , here we have two classes : MyClass is just something very ordinary and nothing special . It has two instance attributes : x and y.MyList , on the other hand , should be a class...
Define what class contains
Python : I have two 1-dimensional numpy.ndarray objects , and want to work out which elements in the first array are within dx of any element in the second.What I have currently is which returns a timeit result as followsWhat 's the best way to optimise the find_all_close function , especially if a and b are guaranteed...
What 's the most efficient way to find which elements of one array are close to any element in another ?
Python : I am currently writing a program to model Dijkstra 's algorithm , however I am having some trouble the graph in its current form below : I want to get the graph in the form such as the one belowWould this be possible ? <code> G = [ [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' , ' f ' , ' g ' , ' h ' , ' i ' , ' j ' ...
Converting a graph into dictionary form
Python : Does Python support conditional structure in regex ? If yes , why I ca n't have the following ( using lookahead in the ifpart ) right ? Any way to make Python support it ? Using backreference as the if part works , however : http : //www.regular-expressions.info/conditional.html says Conditionals are supported...
Does Python support conditional structure in regex ?
Python : I have a YAML file that goes as ( just an example ) : I want to read this file , and do some stuff with bs and cs . The problem is that I ca n't read this file as a dictionary using yaml.load ( ) , since it will only give me { ' a ' : { ' b ' : 3 } } . Instead , I want to read it as a list of dictionaries , i....
Read YAML file as list
Python : I am using the Flask-Mail library for my Flask application to send a default welcome email to the user when they sign up to be added to the newsletter . After debugging the library I found that it can only handle one connection at a time to send a message and will then automatically close the connection . If t...
Flask-Mail queue messages to be sent to different emails
Python : I am working on a leetcode problem `` wordLadder '' Given two words ( beginWord and endWord ) , and a dictionary 's word list , find the length of shortest transformation sequence from beginWord to endWord , such that : Only one letter can be changed at a time . Each transformed word must exist in the word lis...
Exhaustively get all the possible combinations of a word of three lettters
Python : I was just looking at the implementation of functools.lru_cache , when I stumbled across this snippet : I am familiar with circular and doubly linked lists . I am also aware that new_list = my_list [ : ] creates a copy of my_list.When looking for slice assignments or other implementations of circular doubly li...
What is happening when I assign a list with self references to a list copy with the slice syntax ` mylist [ : ] = [ mylist , mylist , ... ] ` ?
Python : I have the following dictionary : And for this dictionary I want write a function that returns the three key-value pairs that have the highest values ( So in this case key 18 , 19 , 20 ) .I came up with the following : This gives me a list of the max-values I want to lookup . But how do I proceed from here ? I...
Returning the three maximal values in a dictionary
Python : I 've run into this problem a few times in different situations but my setup is the following : I have two Django models files . One that contains User models and CouponCodes that a user can use to sign up for a Course . Those are both in the account/models.py file . Course and the related many-to-many field a...
Python/Django : Why does importing a module right before using it prevent a circular import ?
Python : When I had a list that was in format of I could use However now lets say I have multiple values such as I have no idea how to go about creating a dict so that it would show the first name as the key and the following values as the value.Thanks in advance <code> list1 = [ [ James,24 ] , [ Ryan,21 ] , [ Tim,32 ]...
Converting List to Dict
Python : I am wanting to check if a list has a specific sequence of elements . I have sorted the list which contains 7 elements , I now want to check of the first 4 are the same as each other and the last 3 are the same as each other . For what I want to achieve to be True the list would be like this : I hope this make...
Checking a List for a Sequence
Python : In the following data , I am trying to run a simple markov model.Say I have a data with following structure : Block M represents data from one set of catergories , so does block S.The data are the strings which are made by connecting letter along the position line . So , the string value for M1 is A-T-C-G , an...
How to read two lines from a file and create dynamics keys in a for-loop ?
Python : I have the following list of strings : I want to obtain a list that has , say , these same elements repeated n times . If n=3 I 'd get : What I am trying is this : But what I obtain is this : If I try this : I obtain : What am I missing ? <code> l1 = [ 'one ' , 'two ' , 'three ' ] l2 = [ 'one ' , 'one ' , 'one...
Python : expand list of strings by adding n elements for each original element
Python : I am implementing an array-like object that should be interoperable with standard numpy arrays . I just hit an annoying problem that narrows down to the following : This yields the following output : Clearly , rather than calling MyArray ( ) .__rmul__ ( array ( [ 1,2,3 ] ) ) as I had hoped , __rmul__ is called...
numpy coercion problem for left-sided binary operator
Python : I 'm creating an application with python to calculate duct-tape overlapping ( modeling a dispenser applies a product on a rotating drum ) .I have a program that works correctly , but is really slow . I 'm looking for a solution to optimize a for loop used to fill a numpy array . Could someone help me vectorize...
Vectorize a for loop in numpy to calculate duct-tape overlaping
Python : I understand there are at least 3 kinds of methods in Python having different first arguments : instance method - instance , i.e . selfclass method - class , i.e . clsstatic method - nothingThese classic methods are implemented in the Test class below including an usual method : In Python 3 , the unknown_mthd ...
Are there more than three types of methods in Python ?
Python : I am working on an interactive plotting script using matplotlib version 3.2.2 and tkinter.When the script is run , the first window looks like this : Furthermore , the rcParams are updated and plotted once the Plot figure button is clicked : If I now hit the button Change plot settings and change for instance ...
Matplotlib rcParams ignored when plotting
Python : I 'm using the Mirametrix S2 gaze tracking device . In the API docs ( v1.1 ) , it says that the ENABLE_SEND_GPI command allows a tracking client to insert data into the gaze stream . Copying some of the example code , I tried the following : I get the following in response : I 've tried many different combinat...
Mirametrix S2 gaze tracker : Sending general purpose input ( GPI ) values always fails
Python : What 's the rationale behind not allowing * in relative imports ? e.g.or doing a relative import directly : <code> from ..new_tool import * import ..new_tool
python : What 's the rationale behind not allowing * in relative imports ?
Python : The intended objective of function foo is to add the number provided as argument to the list and , in case it is 0 , reset the list . First I wrote this program : output : but it looks like bar = [ ] is ignored . Then I changed bar = [ ] with bar.clear ( ) and it works as I thought : output : I have n't unders...
How is list.clear ( ) different from list = [ ] ?
Python : I am trying to create a custom estimator based on scikit learn . I have written the below dummy code to explain my problem . In the score method , I am trying to access mean_ calulated in fit . But I am unable to . What I am doing wrong ? I have tried many things and have done this referring three four article...
Custom scikit-learn scorer ca n't access mean after fit
Python : I want to use Keras Resnet50 model using OpenCV for reading and resizing the input image.I 'm using the same preprocessing code from Keras ( with OpenCV I need to convert to RGB since this is the format expected by preprocess_input ( ) ) .I get slightly different predictions using OpenCV and Keras image loadin...
Resnet50 produces different prediction when image loading and resizing is done with OpenCV
Python : I want to be able to do something like : In other words , is there a hashable equivalent for Counter ? Note that I ca n't use frozenset since I have repeated elements that I want to keep in the key.Edit : In my actual application , the objects in foo may not be comparable with each other so the list can not be...
Unordered list as dict key
Python : I have 2 models that look like this : models.pyThen in the admin , I have inlined the related models to make it easy to make changes regardless of the object type you have open.admin.pyHowever , if you add a Client to a Deal and then open the Client detail page , the corresponding deal does not appear . Is the...
Django related model not updating related object in admin
Python : I am trying to implement a series of statistical operations , and I need help vectorizing my code.The idea is to extract NxN patches from two images , the compute a distance metric between these two patches.To do this , first I construct the patches with the following loops : This takes about 10 seconds to com...
Advice on vectorizing block-wise operations in Numpy
Python : This one has me entirely baffled.This code works perfectly with the collections line commented out . However , when I comment out the row = dict line and remove the comment from the collections line things get very strange . There are about 4 million of these rows being generated and appended to asset_hist.So ...
Python OrderDict sputtering as compared to dict ( )
Python : It is well known , that small bytes-objects are automatically `` interned '' by CPython ( similar to the intern-function for strings ) . Correction : As explained by @ abarnert it is more like the integer-pool than the interned strings.Is it possible to restore the interned bytes-objects after they have been c...
Is it possible to restore corrupted “ interned ” bytes-objects
Python : Here is some code I wrote for parallelizing the creation of a dictionaryparallelize.pyHere is the output for size 1 mil with threshold 1 milHere is output for size = 10mil with threshold 1 milHere is the output for size 100 mil with threshold 10 mil , the worst part here is even before the combining , the map_...
Python3 parallel code via multiprocessing.pool is slower than sequential code
Python : I am building a Python utility that will involve mapping integers to word strings , where many integers might map to the same string . From my understanding , Python interns short strings and most hard-coded strings by default , saving memory overhead as a result by keeping a `` canonical '' version of the str...
In Python , why do separate dictionary string values pass `` in '' equality checks ? ( string Interning Experiment )
Python : Suppose you use a transaction to process a Stripe payment and update a user entity : It is possible that the Stripe API call succeeds but that the put fails because of contention . The user would then be charged , but his account would n't reflect the payment.You could pull the Stripe API call out of the trans...
GAE/P : Transaction safety with API calls
Python : Given a list [ 2,8,13,15,24,30 ] , all the elements of which are supposed to be in range ( 31 ) . Now I want to slice it into 3 lists , first list with numbers from 0 to 10 , the second one with numbers from 11 to 20 , and the others into the rest.Here is my ugly code : I do n't think this is a good way to do ...
Elegant way to slice a list with a condition
Python : Consider the following session . How are the differences explained ? I thought that a += b is a syntactical sugar of ( and thus equivalent to ) a = a + b . Obviously I 'm wrong.Thank you <code> > > > import numpy as np > > > a = np.arange ( 24 . ) .reshape ( 4,6 ) > > > print a [ [ 0 . 1 . 2 . 3 . 4 . 5 . ] [ ...
Processing data by reference or by value in python
Python : For example : But os.__dict__ shows there is a __dict__ attribute . <code> > > > import os > > > '__dict__ ' in dir ( os ) False
Why does dir of a module show no __dict__ ? ( python )
Python : given two general numpy 1-d arrays ( no guarantees about values whatsoever ) , I need to check if one is a sub-array of the other.It 's short and easy to do by casting to strings , but probably not the most efficient : is there an efficient builtin/native numpy way to do this ? <code> import numpy as npdef is_...
Numpy : check if 1-d array is sub-array of another
Python : I look up online and know that list.pop ( ) has O ( 1 ) time complexity but list.pop ( i ) has O ( n ) time complexity . While I am writing leetcode , many people use pop ( i ) in a for loop and they say it is O ( n ) time complexity and in fact it is faster than my code , which only uses one loop but many lin...
Python list.pop ( i ) time complexity ?
Python : I want to use a function f ( x ) in python . Something like ax^2 + bx + c ( polynomials ) . I want to do that using a for loop and a list . This is what I have so far : for example : when I fill in f ( [ 5,2,3 ] ,5 ) I have to get:3*5^0 + 2*5^1 + 5*5^2 . Does somebody know how I can change my code so the outpu...
Using a normal function f ( x ) in python
Python : I am using django-haystack and I am trying to implement a way to append the page number to a pdf link in order to open it in the specific page . My goal is to open the pdf in the page where the first hit is found . I know the position of the hit in my document and the position where the page changes . For exam...
Django pass Haystack highlighter result to a view
Python : I understand that the python builtin id ( ) returns an ID that is unique for the lifetime of an object . Objects with non-overlapping lifetimes , I understand , can end up with the same ID . However , I am trying to understand this rather confusing behavior : And in fact across multiple interpreter instances ,...
Repeatable id clashes on python objects
Python : I 'm trying to convert numbers to excel column letters.Code : Desired output : Actual output : <code> def num2col ( num ) : letters = `` while num : mod = num % 26 num = num // 26 letters += chr ( mod + 64 ) return `` .join ( reversed ( letters ) ) print num2col ( 25 ) , num2col ( 26 ) , num2col ( 27 ) print n...
Python character function , where is the `` Z '' ?
Python : I 've got some code ( that someone else wrote ) : which I think could be re-written as : This would of course fail if someone passed in attrs=None , but is that something to be expected ? Is there a penalty for the attrs= { } ( extra wasted dict creation ? ) I 'm still too new to python to answer these questio...
Best way to deal with default params in Python ?
Python : I try to concatenate the following strings to a pathleads to To get to the desired outcome I need to remove the first forward slash in the variable lpIs there a more elegant to do it as I do not want to parse all identifiers for a forwarding slash in the beginning ? <code> mr = `` /mapr '' cn = `` 12.12.12 '' ...
connecting multiple strings to path in python with slashes
Python : I have a dictionary that needs to be sorted . I understand that a dictionary can not be sorted , so I am building a list to perform a sort based upon the index . The problem I am having is that there are duplicate values across multiple keys ; also , the values can be multiple lists.Dictionary : I need to be a...
Sorting a dictionary with multiple sized values
Python : I have a greyscale image in numpy array format ( standard OpenCV format ) . Normal image , uint8 , all values between 0 and 255 . When I run : I get : But when I run : I get : And what 's really weird is that if I resize the pyplot image window , those line artifacts change in width . What 's up with this ? I ...
Artifacts in PyPlot vs. OpenCV imshow
Python : How can I append or insert a class attribute into its sub-elements , but only for direct children and then to repeat it for the next class and sub-elements.In the docs it is referenced here pyquery manipulatingSampleSo for each race classappend it into its sub-elements called nomination as raceid so nomination...
PyQuery How do I append and rename an element into each of its subelements
Python : The Python Language Reference specifies object.__await__ as follows : object.__await__ ( self ) Must return an iterator . Should be used to implement awaitable objects . For instance , asyncio.Future implements this method to be compatible with the await expression.That 's it . I find this specification very v...
Precise specification of __await__
Python : For example I get following input : And I need to get following list : Here is my code , but I do n't know how to deal with minuses.warning : I can not use any libraries except re and math . <code> -9x+5x-2-4x+5 [ '-9x ' , '5x ' , '-2 ' , '-4x ' , ' 5 ' ] import retext = '-3x-5x+2=9x-9'text = re.split ( r'\W '...
How to split algebraic expressions in a string using python ?
Python : I have a table with keywords associated with articles , looks like this : I need to get a sort of a pivot table : It means , that the pair ( A , B ) occurs in two articles ( # 1 and # 2 ) , the pair ( A , C ) occurs in just one article ( # 1 ) , etc.What is the most Pythonic way to do that ? I tried Pandas piv...
Cross tabulate counts between pairs of keywords per group with pandas
Python : I would like to vectorize this NumPy operation : where idx contains axis-0 index to an x slice . Is there some simple way to do this ? <code> for j in range ( yt ) : for i in range ( xt ) : y [ j , i ] = x [ idx [ j , i ] , j , i ]
NumPy : Evaulate index array during vectorized assignment
Python : I am trying to calculate the # of days between failures . I 'd like to know on each day in the series the # of days passed since the last failure where failure = 1 . There may be anywhere from 1 to 1500 devices.For Example , Id like my dataframe to look like this ( please pull data from url in the second code ...
Date Difference Between Two Device Failures
Python : Just curious if there is a way to both print and return within one function without assigning the output to variable ? Consider this code : Is there a way to reference that variable stored for the purpose of return statement ? <code> def secret_number ( secret_number_range ) : return random.randrange ( 1 , sec...
Returning and printing without assigning to variable ?
Python : I have an array , given number of items in a group and number of groups , I need to print the array cyclically in a loop.Array- [ 1,2,3,4,5,6 ] Group- 4Iterations- 7Output should be : <code> [ ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' ] [ ' 5 ' , ' 6 ' , ' 1 ' , ' 2 ' ] [ ' 3 ' , ' 4 ' , ' 5 ' , ' 6 ' ] [ ' 1 ' , ' 2 ' , ...
Display grouped list of items from python list cyclically
Python : Input data is a 2D array ( timestamp , value ) pairs , ordered by timestamp : I want to find time windows where the value exceeds a threshold ( eg . > =4 ) . Seems I can do the threshold part with a boolean condition , and map back to the timestamps with np.extract ( ) : But from that I need the first and last...
Threshold numpy array , find windows
Python : I have defined the following class : And the following code works : with output : But this does not : It gives the following error : Which is because the point class is being fed into the int mul function , I 'm assuming . How can I keep the definition of point contained in the Point class and still have 3*y r...
Overiding __mul__ in two dimensional vector class to preserve commutivity
Python : Can I implement a generic descriptor in Python in a way it will support/respect/understand inheritance hierarchy of his owners ? It should be more clear in the code : gist - almost the same code snippet on gist <code> from typing import ( Generic , Optional , TYPE_CHECKING , Type , TypeVar , Union , overload ,...
typing : How to bind owner class to generic descriptor ?
Python : Running : Books.referTable being a data descriptor is not shadowed by book.__dict__ [ 'referTable ' ] : The property ( ) function is implemented as a data descriptor . Accordingly , instances can not override the behavior of a property.To shadow it , instead of property built-in descriptor i must use my own de...
Built-in non-data version of property ?
Python : The problem is a list of room numbers and guest details I ripped straight from a txt file that needs to be put into a dictionary with the room number as the keys and the details as the values.The guest list is literally a list , each item represents room number , guest name , arrival , departure dates . Rooms ...
How do I sort a dictionary ?
Python : This code works but I was wondering if there is a more pythonic way for writing it.word_frequency is a dictionary of lists , e.g . : Is there a more elegant way of writing this loop ? <code> word_frequency = { 'dogs ' : [ 1234 , 4321 ] , 'are ' : [ 9999 , 0000 ] , 'fun ' : [ 4389 , 3234 ] } vocab_frequency = [...
Pythonic way of executing a loop on a dictionary of lists
Python : I have the following directory structurewith main_code.py just importing mylib : and mylib.py just importing time : Now it turns out that mylib.py imports libs/time.py and not the built-in standard library time . Is there any way to get the 'normal ' behavior , i.e . that mylib.py imports the built-in standard...
How to import standard library instead of same-named module in module path
Python : I have an enum for which some of the members are deprecated : How do it get the following behavior : When somebody writes Foo.BAR , everything behaves normallyWhen somebody writes Foo.BAZ , a DeprecationWarning is issued using warnings.warn ( `` BAZ is deprecated '' , DeprecationWarning ) . Afterwards everythi...
How do I detect and invoke a function when a python enum member is accessed
Python : Can someone please explain this behaviour : <code> > > > a = { 'hello ' : 'world ' , 'good ' : 'food ' } > > > b = [ 1,2 ] > > > b = b + aTraceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > TypeError : can only concatenate list ( not `` dict '' ) to list > > > b += a > > > b [ 1...
Why does += operator work differently than + and assign operator for python dictionary ?
Python : Suppose I have a dataframe of which one column is a list ( of a unknown values and length ) for example : I came across this solution but it isnt what I am looking for.How best to extract a Pandas column containing lists or tuples into multiple columnsin theory the resulting df would look likeSee above <code> ...
How do I perform One Hot Encoding on lists in a pandas column ?
Python : In Python the symbol int is used both as a type and a built-in function . But when I use int in the REPL , or ask for its type , the REPL tells me it is a type.This is fine , but int is also a built-in function : it is listed in the table of built-in functions right in the Python documentation.Other built-in f...
Does Python assume a symbol is a type before trying to see if it is a function ?
Python : Now , when I enter : I get : which does n't make a whole lot of sense to me . Can anybody explain that simply ? <code> two_d = np.array ( [ [ 0 , 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 , 9 ] , [ 10 , 11 , 12 , 13 , 14 ] , [ 15 , 16 , 17 , 18 , 19 ] , [ 20 , 21 , 22 , 23 , 24 ] ] ) first = np.array ( ( True , True ,...
Unexpected behaviour when indexing a 2D np.array with two boolean arrays
Python : In the code below , I import a saved sparse numpy matrix , created with python , densify it , add a masking , batchnorm and dense ouptput layer to a many to one SimpleRNN . The keras sequential model works fine , however , I am unable to use shap . This is run in Jupyter lab from Winpython 3830 on a Windows 10...
Error using shap with SimpleRNN sequential model
Python : How can I write a function `` fmap '' , with this properties : ( I search a kind of `` fmap '' in haskell , but in python3 ) .I have a very ugly solution , but there is certainly a solution more pythonic and generic ? : <code> > > > l = [ 1 , 2 ] ; fmap ( lambda x : 2*x , l ) [ 2 , 4 ] > > > l = ( 1 , 2 ) ; fm...
How can I write a function fmap that returns the same type of iterable that was inputted ?
Python : I have a mercurial hook like so : with the code looking like this : but this hook runs on commands that use the commit logic to do something else , in my case hg shelve . is there a way to get the command that the user has input to avoid running the hook on that command ? perhaps something like this : <code> [...
ignore certain mercurial commands in mercurial hook
Python : When i changed two words in a string with other two words using re.sub i got the output . But when i tried that with numbers output is not coming correctlyi do n't know why this happens could u please tel me how to use this Thanks in advance <code> > > > import re > > > a='this is the string i want to change '...
Multiple substitutions of numbers in string using regex python