text
stringlengths
46
37.3k
title
stringlengths
12
162
Python : I want to create 2 new columns which would give me the closest value and ID to a certain value . This is how my df in python is structured : Essentially , I want to create a new column ( called 'closest_time ' & 'closest_price ' ) which would be the closest p_price to the x_price for that group only ( hence th...
Finding closest value while grouping by a column
Python : A discussion with a friend led to the following realization : The second example is clearly more efficient simply by reducing the number of instructions.My question is , is there a name for this optimization , and why does n't it happen in the first example ? Also , I 'm not sure if this is a duplicate of Why ...
Optimization of arithmetic expressions - what is this technique called ?
Python : Suppose I have 2 matrices M and N ( both have > 1 columns ) . I also have an index matrix I with 2 columns -- 1 for M and one for N. The indices for N are unique , but the indices for M may appear more than once . The operation I would like to perform is , Is there a more efficient way to do this other than a ...
numpy : efficiently summing with index arrays
Python : My laptop has 4 cores , and after some simple testing , I found my CPU usage is at 100 % when I 'm using multiprocessing with 4 jobs or more , about 75 % with 3 jobs , about 50 % with 2 jobs and 25 % with 1 job . This makes perfect sense to me.Then I found that my program runs my jobs 4 times faster with multi...
Multiprocessing speed up vs number of cores
Python : I just read another users question while looking for a way to compute the differences in two lists.Python , compute list differenceMy question is why would I dorather than doingedit : just noticed the second diff function actually returned the similarities . It should be correct now . <code> def diff ( a , b )...
Why use a set for list comparisons ?
Python : What 's going on belowWhy does the iteration stop at 8 without any error ? Reproducible on both python2.7 and python 3.5 . <code> > > > d = { 0:0 } > > > for i in d : ... del d [ i ] ... d [ i+1 ] = 0 ... print ( i ) ... 01234567 > > >
Modifying a dict during iteration
Python : simple model ( models.py ) : simple factory ( test_factories.py ) : In manage.py shell : current date is 2017-08-16 and fake date is 1999-09-09 . Inside freeze_time , date.today ( ) give fake date but factoryboy is not affected by freezegun . It still give real current date.Is this bug ? If yes , bug with fact...
factoryboy not working with freezegun
Python : Today I 'm requesting help with a Python script that I 'm writing ; I 'm using the CSV module to parse a large document with about 1,100 rows , and from each row it 's pulling a Case_ID , a unique number that no other row has . For example : As you can see , this list is quite an eyeful , so I 'd like to inclu...
Collapse sequences of numbers into ranges
Python : I have a problem I think should be easy but ca n't find solution , I want to find the matching values in two arrays , then use the indices of one of these to find values in another arrayClearly the above method does work , but it 's very slow , and this is just an example , in the work I 'm actually do a , b1 ...
Return values from array based on indices of common values in two other arrays
Python : So I have these two df 's : df A : df B : What I would like to do is add a third column to df A based on the correspondence of df B regarding TYPE : I tried this code : But I think I am making more mistakes . Hopefully somebody can help me . Thanks in advance . <code> ID TYPE 1 A2 B3 C4 A5 C TYPE MEASUREA 0.3B...
Pandas dataframe create a new column based on columns of other dataframes
Python : I 'm writing some integration tests that involve a Python application running under uwsgi.To test an aspect of this , I am running an uwsgi spooler , which requires that the master process is running.If pytest has a failed test , it returns a non-zero exit code , which is great.Without the master process , the...
How to get uwsgi to exit with return code of any failed sub-process
Python : I have been trying to wrap my head around why this is happening but am hoping someone can shed some light on this . I am trying to tag the following text : using the following code : and am getting the following result : And I do n't get it . Does anyone know what is the reason for this inconsistency ? I am no...
Is POS tagging deterministic ?
Python : Say I create python lists in two ways.In the first case I use simple assignment : In the second case I use append ( ) method on list : But I get unexpected ( for me ) output : What happens internally with Python memory management ? Why do the 'same ' lists have different sizes ? <code> my_list = [ ] print ( my...
Why do lists with the same data have different sizes ?
Python : I have a grid of circular data , e.g . the data is given by its angle from 0 to π . Within this data , I have another smaller grid.This might look like this : What I want to do is to interpolate the black data on the red dots . Therefore I 'm using scipy.interpolate.griddata . This will give me the following r...
Python : How to unwrap circular data to remove discontinuities ?
Python : I have noticed that attempting to speed up numpy code that involves generating large numbers of random numbers by vectorising the python for loops out can have the opposite result and can slow it down . The output of the following bit of code is : took time 0.588 and took time 0.789 . This goes against my intu...
Numpy random number generation runs slower after being vectorised
Python : We are migrating from one content system into another and have tons of HTML where there are lines , for example , like this : I am looking for a way to strip HTML with Python where there is no text output to the screen . So a line similar to this would be stripped.And , this is just one of MANY examples of lin...
Removing empty nodes from HTML
Python : I am trying to come up with a way to generate all possible unique strings from an alphabet of 20 characters where the order within the string does n't matter , and the length of the string can vary . So , for instance , for a string of length 3 , the possible strings would be AAA , AAB , AAC , etc. , but would...
Variable number of predictable for loops in Python
Python : I am working on Python 2.7 and I am trying to overload __getitem__ and __setitem__ from a class that inherits list . Let 's say I have this class A : With square brackets , A.__getitem__ or A.__setitem__ should be called . Normally it is like that , but when I use [ : ] the parent implementation is called inst...
Why are my subclass 's __getitem__ and __setitem__ not called when I use [ : ] ?
Python : I have array and need max of rolling difference with dynamic window.So first I create difference by itself : Then replace upper triangle matrix to 0 : Last need max values per diagonal , so it means : So expected output is : What is some nice vectorized solution ? Or is possible some another way for expected o...
Max value per diagonal in 2d array
Python : I am trying to learn python language and it 's concept . I wrote some code to play with multithreading . But i notice that there is no execution time difference between multi and single threading.The machine which is to run script has 4 core/thread . Each file 's size in the Raw Data is bigger than 25 mb . So ...
Why is there no execution time difference between multithreading and singlethreading
Python : Apologize if this has been asked before , somehow I am not able to find the answer to this.Let 's say I have two lists of values : that represents indexes of rows and columns respectively . The two lists combined signified sort of coordinates in the matrix , i.e ( 0,0 ) , ( 1,2 ) , ( 2,3 ) .I would like to use...
How to change dataframe cells values with `` coordinate-like '' indexes stored in two lists/vectors/series ?
Python : Can I call a method to process data by combining strings ? For example , it is OK to type data.image.truecolor ( ) in code ? My problem is : if I have a data object named data ( not a string ) , how to combine `` .image.truecolor '' sting to call method to process the data ? It is like : Of course , it is fail...
How to call method by string ?
Python : Currently when I want to define a setter and leave getter alone I do this : Is there any way to make it shorter ? I 'd like to skip this part as it always look the same : <code> @ propertydef my_property ( self ) : return self._my_property @ my_property.setterdef my_property ( self , value ) : value.do_some_ma...
Defining setter in a shorter way
Python : There are three types of foods were provided i.e . meat , cake and pizza and N different stores selling it where , i can only pick one type of food fromeach store . Also I can only buy items in A , B and C numbers where ' A ' means , Meat from total ' A ' number of different stores ( see example ) . My task is...
Maximize consumption Energy
Python : I want to implement the following algorithm , taken from this book , section 13.6 : I do n't understand how to implement the update rule in pytorch ( the rule for w is quite similar to that of theta ) .As far as I know , torch requires a loss for loss.backwward ( ) .This form does not seem to apply for the quo...
Pytorch : How to create an update rule that does n't come from derivatives ?
Python : I have one column containing all the data which looks something like this ( values that need to be separated have a mark like ( c ) ) : And I want it split into two columns looking like this : Question 2 : What if the countries did not have a pattern like ( c ) ? <code> UK ( c ) LondonWalesLiverpoolUS ( c ) Ch...
How do I create a new column in a dataframe from an existing column using conditions ?
Python : Many regex engines match . * twice in a single-line string , e.g. , when performing regex-based string replacement : The 1st match is - by definition - the entire ( single-line ) string , as expected.In many engines there is a 2nd match , namely the empty string ; that is , even though the 1st match has consum...
Why do some regex engines match . * twice in a single input string ?
Python : I have a python module that defines a number of classes : From within the module , how might I add an attribute that gives me all of the classes ? dir ( ) gives me the names of everything from within my module , but I ca n't seem to figure out how to go from the name of a class to the class itself from within ...
How can I dynamically get the set of classes from the current python module ?
Python : I want to open Windows Explorer and select a specific file.This is the API : explorer /select , '' PATH '' . Therefore resulting in the following code ( using python 2.7 ) : The code works fine , but when I switch to non-shell mode ( with pythonw ) , a black shell window appears for a moment before the explore...
Launch a GUI process without spawning a black shell window
Python : I have 2 codes which did the same work as which i am asking , but still i did n't get any useful or better code for my data set to make it useful for me , First let me clear what i am doing .I have 2 TEXT files , one name as input_num and second named as input_data as it is clear from names that input_num.txt ...
Length cutting through file handling
Python : I have following datasetCode to reproduce : Suppose I have to Change only the maximum value of each group of `` Item '' column by adding 1.the output should be like this : I tried df [ 'New_Count ' ] =df.groupby ( [ 'Item ' ] ) [ 'Count ' ] .transform ( lambda x : max ( x ) +1 ) but all the values in `` Count ...
How to change only the maximum value of a group in pandas dataframe
Python : I am trying to get the email provider from the mail column of the Dataframe and create a new column named `` Mail_Provider '' . For example , taking gmail from a @ gmail.com and storing it in `` Mail_Provider '' column . Also I would like to extract Country ISD fro Phone column and Create a new column for that...
Extracting particular characters/ text from DataFrame column
Python : I am using Django and I am wondering how I can accomplish this . It works fine in python in Linux but the HTML Templating language keeps saying it can not parse the array.It says it can not parse the remainder and then it displays the list . <code> { % if myvalue in [ `` 128 '' , '' 256 '' , '' 512 '' , '' 768...
Python Value in List
Python : James Powell , in his short description for an upcoming presentation , says he is the proud inventor of one of the gnarliest Python one-liners : I am trying to figure out this generator , and since I live with Python 2.7.x , I 'm also tripping over the ( yield from g ) expression.How do I read this , and what ...
Python : understanding ( None for g in g if ( yield from g ) and False )
Python : Assuming that the computer running this program has an infinite amount of memory , I 'm interested in where Python will break when running the following : For fun , I implemented hyperoperators in python as the module hyperop . One of my examples is Graham 's number : The condensed version of the class hyperop...
What technical limitations prevent the calculation of Graham 's number in python ?
Python : Short version : I want to crate function which replace all named groups in regular expression with coresponding data from datadict.For example : But i have no idea how to do it.Some addtional info : I have code which iterate trough list of tuples containing name and pattern and trying to use re.search . In cas...
How to compose string from regex pattern with named groups and datadict in python ?
Python : In the question What does the `` yield '' keyword do ? , I found a Python syntax being used that I did n't expect to be valid . The question is old and has a huge number of votes , so I 'm surprised nobody at least left a comment about this function definition : What I tried to get this sort of syntax evaluate...
Is it possible to def a function with a dotted name in Python ?
Python : I have a list of text files file1.txt , file2.txt , file3.txt .. filen.txt that I need to shuffle creating one single big file as result *.Requirements : 1 . The records of a given file need to be reversed before being shuffled 2 . The records of a given file should keep the reversed order in the destination f...
Shuffle the records of a list of text files in one single file
Python : Certain list comprehensions do n't work properly when I embed IPython 0.10 as per the instructions . What 's going on with my global namespace ? <code> $ python > > > import IPython.Shell > > > IPython.Shell.IPShellEmbed ( ) ( ) In [ 1 ] : def bar ( ) : pass ... : In [ 2 ] : list ( bar ( ) for i in range ( 10 ...
How do I embed IPython with working generator expressions ?
Python : Is there a simple and direct way to add 'one ' at float number in Python ? I mean this : This is not what I want , because it gives me 0.0144000000001 . <code> if a == 0.0143 : a = plus ( a ) assert a == 0.0144def plus ( a ) : sa = str ( a ) index = sa.find ( ' . ' ) if index < 0 : return a+1 else : sb = ' 0'*...
How to plus one at the tail to a float number in Python ?
Python : I was messing around with a small custom data object that needs to be hashable , comparable , and fast , when I ran into an odd-looking set of timing results . Some of the comparisons ( and the hashing method ) for this object simply delegate to an attribute , so I was using something like : However upon testi...
Why are explicit calls to magic methods slower than `` sugared '' syntax ?
Python : I solved a problem on Project Euler but it took about 4 minutes to run , which is above the recommended time , so I was looking through the different solutions in the forum . One of them included the symbol < < in a list comprehension . This is what it looked likeI ca n't find anywhere what exactly this < < sy...
What does < < do in Python ?
Python : Perhaps not such a big deal , but it breaks my heart to follow this : deltas = data [ 1 : ] - data [ : -1 ] with this : For this particular example ... is there a better way to do the cleansing part ? Question part two : What if the cleansing rules are more complicated , or less complicated than this example ....
Can I cleanse a numpy array without a loop ?
Python : I have difficult time understanding how the shape of resultant array be determined after slicing in numpy . For example I am using the following simple code : Output of this is : In both of these cases , content is same ( as it should be ) . But they differ in shapes . So , how does the resultant shape is dete...
Determining the shape of result array after slicing in Numpy
Python : Is the following syntax not supported by f-strings in Python 3.6 ? If I line join my f-string , the substitution does not occur : returns : If I remove the line-join : it works as expected : In PEP 498 , backslashes within an f-string are expressly not supported : Escape sequences Backslashes may not appear in...
Is line-joining unsupported by f-strings ?
Python : I have several decorators on each function , is there a way to pack them in to one instead ? change to : <code> @ fun1 @ fun2 @ fun3def do_stuf ( ) : pass @ all_funs # runs fun1 fun2 and fun3 , how should all_funs look like ? def do_stuf ( ) : pass
How can I pack several decorators into one ?
Python : When I easy_install some python modules , warnings such as : sometimes get emitted . Where ( what package / source file ) do these messages come from ? Why is referencing __file__ or __path__ considered a bad thing ? <code> < some module > : module references __file__ < some module > : module references __path...
warnings emitted during 'easy_install '
Python : From a numeric age pandas column , discretize as ageD with qcut , we create open bounds from the qcut bounds : From Index ( [ u ' [ 5 , 30 ] ' , u ' ( 30 , 70 ] ' ] , dtype='object ' ) we make bopens : Then we convert categorical variable into dummy/indicator variables with get_dummies : I want to enrich the d...
Create open bounds indicators from pandas get_dummies on discretized numerical
Python : Say I have one list , And another , ( You can imagine that the second list was created with an itertools.groupby on an animal being a house pet . ) Now say I want to give the first list the same sublist structure as the second.I might do something like this : Which I have n't totally debugged but I think shoul...
Copying sublist structure to another list of equal length in Python
Python : Consider the following arrangement of letters : Start at the top letter and choose one of the two letters below , Plinko-style , until you reach the bottom . No matter what path you choose you create a four-letter word : BOND , BONE , BORE , BORN , BARE , BARN , BAIN , or BAIT . The fact that DENT reads across...
How to build a Plinko board of words from a dictionary better than brute force ?
Python : I am trying to calculate all the distances between approximately a hundred thousand points . I have the following code written in Fortran and compiled using f2py : I am compiling the fortran code using the following python code setup_collision.py : Then running it as follows : Using this code with 30,000 atoms...
Why is my Fortran code wrapped with f2py using so much memory ?
Python : I am setting up the following example which is similar to my situation and data : Say , I have the following DataFrame : Now , I have the following function , which returns the discount amount based on the following logic : Now I want the resulting DataFrame : So I decided to call series.map on the column pric...
Setting value to a copy of a slice of a DataFrame
Python : I have a script where I 'm loading a file which takes a while because there is quite much data to read and to prevent the user from terminating the process I want to show some kind of loading indication . I thought this was a good opportunity to learn how to use the multiprocessing module so I wrote this examp...
Only one process prints in unix , multiprocessing python
Python : I was working on a Flask project , getting some data from an API wrapper . The wrapper returned a generator object , so I print the values ( for obj in gen_object : print obj ) before passing it to Flask 's render_template ( ) . When requesting the page while printing the objects , the page is empty . But remo...
Do Python generator objects become `` unusable '' after being traversed ?
Python : I have been absolutely racking my brain over this , and ca n't seem to work out how to get around the issue . Please note that I have cut alot of irrelevant fields out of my modelsI am in the middle of coding up my SQL-Alchemy models , and have encountered the following issue : Due to multiple billing systems ...
Inheritance + Foreign Keys
Python : I have a series of input files such as : in my code I am trying to capture 2 elements from each line , the first is the number after where it says exon , the second is the gene ( the number and letter combo surrounded by `` '' , e.g . `` KDM4A '' . Here is my code : for some reason start works fine but genes i...
splitting lines with `` from an infile in python
Python : I 'm trying to perform basic affine transformation using pivot points.On both images I made 3 points ( R , G & B ) and saved them in separate images ( 'earth_keys.png ' for 'earth.png ' and 'earth2_keys.png ' for 'earth2.png ' ) . All I want is to match pivot points on 'earth2.png ' with pivot points on 'earth...
OpenCV affine transformation wo n't perform
Python : Just a quick silly question . How do I write a trailing slash in a raw string literal ? <code> r = r'abc\ ' # syntax errorr = r'abc\\ ' # two slashes : `` abc\\ ''
Trailing slash in a raw string
Python : I 'm trying to install a package with setuptools including console_scripts on Windows 7 . I 'm trying to change the value of my PYTHONUSERBASE to install into a custom directory with the -- user flag . If I use backslashes in the value of PYTHONUSERBASE , as ineverything works fine . However , if I use a forwa...
Python setuptools is stripping slashes from path arguments on Windows
Python : I have a generative adversarial networks , where the discriminator gets minimized with the MSE and the generator should get maximized . Because both are opponents who pursue the opposite goal.What do I have to adapt , to get a generator model which profits from a high MSE value ? <code> generator = Sequential ...
Maximize the MSE of a keras model
Python : I 've been perusing some of the source code for numpy and I noticed that a lot of the c source code uses the construction @ variablename @ . For example , in the file `` npy_math_complex.c.src '' ( located here ) : What do @ ctype @ and @ c @ mean ? Are these some sort of macros ? I 'm guessing they are n't no...
How is the at sign ( @ ) used in the c source code for numpy ?
Python : I have a pandas dataframe with 2 columns . Some of the MessageID 's end on the same row that they start with the NewMessageID like in index row 0 below . But others like index row 2 doesnt end until index row 4 . I am looking for a clever way to simplify the output in a new dataframe.I am looking for an output...
Pandas How to create a new dataframe with a start and end even if on different rows
Python : EditThe accepted answer works for sets that satisfy the requirements of a strict partially ordered set , so that a directed acyclic graph can be constructed : irreflexivity not a < a : the list does not contain items like [ ' a ' , ' a ' ] transitivity if a < b and b < c then a < c : the list does not contain ...
Logically sorting a list of lists ( partially ordered set - > topological sort )
Python : Let 's say I have a Python 3 source file in cp1251 encoding with the following content : If I run the file , I 'll get this : SyntaxError : Non-UTF-8 code starting with '\xfd ' in file ... on line 1 but no encoding declared ; see http : //python.org/dev/peps/pep-0263/ for detailsThat 's clear and expected - I ...
How does the Python compiler preprocess the source file with the declared encoding ?
Python : Hi I 'm trying to write a module that lets me read and send data via pyserial . I have to be able to read the data in parallel to my main script . With the help of a stackoverflow user , I have a basic and working skeleton of the program , but when I tried adding a class I created that uses pyserial ( handles ...
pyserial with multiprocessing gives me a ctype error
Python : We can initialise a new dict instance from a list of keys : And a querydict is a dict , so this should work , right ? Of course I can do something lame like QueryDict ( 'spam & spam & potato ' ) , but my question : is the .fromkeys method usable at all , or completely broken ? If the former , how do you use it...
Initialising a QueryDict.fromkeys
Python : I want to compare two pandas dataframes and find out the rows that are only in df1 , by comparing the values in column A and B. I feel like I could somehow perform this by using merge but can not figure out..df1df2Dataframe I want to see <code> import pandas as pddf1 = pd.DataFrame ( [ [ 1,11 , 111 ] , [ 2,22 ...
Eliminate pandas dataframe rows with partial matches
Python : I am interfacing a C library with python . I have arrays in numpy that I pass to the library using the ctypes attribute of the array.At some point I need to provide an array to the C library , that is expected to be the transposed of the numpy array a I have . ( Another way of putting it is that the C library ...
Enforcing in-memory transposition of a numpy array
Python : Using default arguments of the form x= { } usually does not accomplish the intended purpose in Python , since default arguments are bound when a function is defined , not called.The convention seems to be to set mutable objects as default arguments with x=None and then check x is None to assign the proper defa...
What is the most Pythonic way to use an empty dictionary as a default argument ?
Python : That looks like : I manage to filter on : stores_grouped.filter ( lambda x : ( len ( x ) == 1 ) ) But when I want to filter on two conditions : That my group has length one and id column is equals 10.Any idea ho do so ? <code> data = { 'year ' : [ '11:23:19 ' , '11:23:19 ' , '11:24:19 ' , '11:25:19 ' , '11:25:...
filtering dataframe on multiple conditions
Python : I have a lower triangular array , like B : I want to flip it to look like : That is , I want to take all the positive values , and reverse within the positive values , leaving the trailing zeros in place . This is not what fliplr does : Any tips ? Also , the actual array I am working with would be something li...
Flip non-zero values along each row of a lower triangular numpy array
Python : I have a dataframe of categories and amounts . Categories can be nested into sub categories an infinite levels using a colon separated string . I wish to sort it by descending amount . But in hierarchical type fashion like shown.How I need it sortedEDIT : The data frame : Note : this is the order I want it . I...
Pandas hierarchical sort
Python : Consider the following minimal example : Running this code with Python 2 raises exception bar , running it with Python 3 raises exception foo . Yet , the documentation for both Python 2 and Python 3 states that raise with no expression will raise `` the last exception that was active in the current scope '' . ...
Scope for `` raise '' without arguments in nested exception handlers in Python 2 and 3
Python : Just as an example , if I created a new environment.Very obviously , in this case , there are only two top-level dependencies that are added in this environment : python and Jupiter . I know that we can export the dependencies according to Sharing an environmentBut see how verbose it is.Is there a way to only ...
Show top level dependencies for a conda managed environment
Python : I have the following dataframe : How can I drop the row second value after False all the the True values till the second True Value till the second False ? Such as for example : Edit 1 : I would like to add 1 more condition on the new df : As you have mentioned in the comment : [ True , True , True , False , T...
How to conditionally drop rows in pandas
Python : I have this simple query written in Django and I want to run my tests with pytest.When I run my tests with Django 's test runner : python manage.py test , I get the expected result : But when I do it with pytest -s , I get : Why is n't pytest converting dates like Django 's test runner ? <code> results = ( sel...
pytest wo n't convert date field to datetime.date object in Django
Python : Are there good ( suitable for using in real projects ) ways or reducing boilerplate in things like thisI want it to look more like this : or ( more realistically ) Is it possible in Python 2.6+ without overt hacks ? @ link super ( ) in Python 2.x without args <code> class B ( A ) : def qqq ( self ) : # 1 unwan...
How to avoid boilerplate when using super ( ... ) in Python 2.6+ ?
Python : I was doing one of the course exercises on codeacademy for python and I had a few questions I could n't seem to find an answer to : For this block of code , how exactly does python check whether something is `` in '' or `` not in '' a list ? Does it run through each item in the list to check or does it use a q...
How exactly does Python check through a list ?
Python : People mentioned in answers a1 , a2 that Due to the way the Python C-level APIs developed , a lot of built-in functions and methods do n't actually have names for their arguments.I found it really annoying cause I 'm not be able to know it by looking at the doc . For instance , eval eval ( expression , globals...
Is there a complete list of built-in functions that can not be called with keyword argument ?
Python : I 'm looking for a way to have a collection of homogeneous objects , wrap them in another object , but have the wrapper object have the same API as the original and forward the corresponding API call to its object members.Some possible solutions that have been considered , but are inadequate : Rewriting the wh...
Wrapping homogeneous Python objects
Python : So i am reading ( and displaying with a tkinter textbox ) data from a serial connection , but i ca n't process the returning data as i would like to , in order to run my tests . In more simple terms , even though the machine response = 0x1 is displayed , i ca n't read it from the global serBuffer.Before displa...
Issue processing data read from serial port , when displaying it in a Tkinter textbox
Python : I have a DataFrame like this : How can I create a new column which enumerates groups of foo per group of [ 'name ' , 'visit ' ] , like this ? <code> name visit foo0 andrew BL a1 andrew BL a2 andrew BL b3 andrew BL b4 bob BL c5 bob BL c6 bob BL d7 bob BL d8 bob M12 e9 bob M12 e10 bob M12 f11 bob M12 g12 carol B...
How to enumerate groups within groups in pandas
Python : I have a list of lists and I 'd like to get the top x lists with the highest values so top 3 max ( list_of_lists ) would return or if I 'm looping through list_of_lists I could append each of the lists with the top x max values to another list of lists , based upon the index of the selected lists.Here 's the c...
How to find the lists with max values in a list of lists ( where nested lists contain strings and numbers ) ?
Python : I can not explain the following behaviour : It seems to be that l1 [ : ] [ 0 ] refers to a copy , whereas l1 [ : ] refers to the object itself . <code> l1 = [ 1 , 2 , 3 , 4 ] l1 [ : ] [ 0 ] = 888print ( l1 ) # [ 1 , 2 , 3 , 4 ] l1 [ : ] = [ 9 , 8 , 7 , 6 ] print ( l1 ) # [ 9 , 8 , 7 , 6 ]
Python : lists and copy of them
Python : I am scraping a page with BeautifulSoup , and part of the logic is that sometimes part of the contents of a < td > tag can have a < br > in it . So sometimes it looks like this : and sometimes it looks like this : I am looping through this and adding to an output_row list that I eventually add to a list of lis...
Python to CSV is splitting string into two columns when I want one
Python : This is the code that I have written . As you can see , it has a button which when clicked opens up a Text where one can enter something . It works , the window resizes if you click the button.But I have noticed that , if I maximize and minimize the window just after starting the program ( i.e . the first thin...
Tkinter - Maximizing and minimizing the window before using any widgets , hides the widgets when I use them
Python : I have the following code in Matlab which I 'm not familiar with : I wrote this following function in Python : I get an error : data is a pandas DataFrame that was read from a CSV file containing triaxial accelerometer data . The axes of the accelerometer data are x , y , and z . The columns for the data frame...
How do I convert matrices from Matlab to Python ?
Python : So I 'm teaching myself Python , and I 'm having an issue with lists . I want to pass my function a list and pop items off it while retaining the original list . How do I make python `` instance '' the passed list rather that passing a pointer to the original one ? Example : Output : [ 0 , 1 , 2 ] [ 5 , 4 , 3 ...
Passing a list while retaining the original
Python : I was reading through the answers earning a `` reversal '' badge and I found a question regarding recursion where the OP did n't bother to do much of their homework assignment up front . Aside from some really funny answers , @ machielo posted an answer in python that I had to run on my machine to get a grip o...
I Do n't Understand This Use of Recursion
Python : How come this code runs for me ? I thought slots worked as a restriction . I 'm running Python 2.6.6 . <code> class Foo ( ) : __slots__ = [ ] def __init__ ( self ) : self.should_not_work = `` or does it ? '' print `` This code does not run , '' , self.should_not_workFoo ( )
I do n't know how to make __slots__ work
Python : I am installing airflow via command : python3 setup.py install . It takes in the requirements file , requirements/athena.txt which is : apache-airflow [ celery , postgres , hive , password , crypto ] ==1.10.1I got an error : To remove this error , I set export SLUGIFY_USES_TEXT_UNIDECODE=yes and export AIRFLOW...
Unable to install Airflow even after setting SLUGIFY_USES_TEXT_UNIDECODE and AIRFLOW_GPL_UNIDECODE
Python : I run yield from generator and yield from list many times . List version gives always better performance , while my intuition tells me rather opposite conclusions - making list requires i.e . memory allocation at startup . Why we can notice such performance differences ? <code> Python 3.6.8 ( default , Oct 7 2...
` yield from ` generator vs ` yield from ` list performance
Python : According to this test : There is no difference between .decode ( ) and unicode ( ) : Am I right ? If so , why do we have two different ways of accomplishing the same thing ? Which one should I use ? Is there any subtle difference ? <code> # -*- coding : utf-8 -*-ENCODING = 'utf-8 ' # what is the difference be...
Difference between decode and unicode ?
Python : I 'm running this SVD solver from scipy with the below code : I expected the printed mean value to be the same each time , however it changes and seems to cycle through a few favourite values . I 'm happy to accept that behaviour as a consequence of the low level optimisation/random seeding.What I do n't quite...
scipy linalg deterministic/non-deterministic code
Python : I 've been reading some of the code in a standard threading library ( Python 2.6 ) and there was a piece of code which made me wonder . It can be shorten to the following structure ( compare to __bootstrap_inner method in threading.py ) : These variables do not go outside of foo scope . Is there any reason to ...
Deleting variables in Python standard libraries
Python : Considder the following interactive exampleDoes anyone know if there is already an implementation somewhere out there with a version of imap ( and the other itertools functions ) such that the second time list ( l ) is executed you get the same as the first . And I do n't want the regular map because building ...
Itertools for containers
Python : Similar questions have been brought ( good speed comparison there ) on this same subject . Hopefully this question is different and updated to Python 2.6 and 3.0.So far I believe the faster and most compatible method ( among different Python versions ) is the plain simple + sign : But I keep hearing and readin...
Speed vs security vs compatibility over methods to do string concatenation in Python
Python : For example : In the above examples the value_counts works perfectly and give the required result . whereas when coming to larger dataframes it is giving a different output . Here the A values are already sorted and counts are also same , but the order of index that is A changed after value_counts . Why is it ...
Pandas Series value_counts working differently for different counts
Python : I am trying to get a conceptual understanding of the nature of Python functions and methods . I get that functions are actually objects , with a method that is called when the function is executed . But is that function-object method actually another function ? For example : If I look at dir ( fred ) , I see i...
Which is more fundamental : Python functions or Python object-methods ?
Python : I have a set of bitstrings : { '0011 ' , '1100 ' , '1110 ' } ( all bitstrings within a set are of same length ) .I want to quickly find the bitstring of same length that has the smallest max-similarity to the set . Max-similarity can be computed as such : I know that I can iterate through all the possible bits...
Search for bitstring most unlike a set of bitstrings