text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
Python : I am attempting to utilize the Presenter-First approach to a new project . I find myself with unittest below . Am I utilizing poor unit testing practices by including so many assertions in this test ? If yes , is the issue with my approach to the test or to the implementation of presenter.setOverview ? In othe... | Presenter-First Unittest with Multiple Assertions |
Python : I have a dictionary surnames : I would like to sum all arrays and save them in the same dictionary so that the sum replaces the array : I tried this : I assume this does n't work because it only sums single values of the same key ? I also tried this : I understand why this does n't work either , but what else ... | Replace values in a dictionary of NumPy arrays and single numbers with sums |
Python : Consider the numpy.array iExample 1index Example 2columnsButLeads to this when I display itHowever , df.T works ! ? QuestionWhy is it necessary for index values to be hashable in a column context but not in an index context ? And why only when it 's displayed ? <code> i = np.empty ( ( 1 , ) , dtype=object ) i ... | Why is it ok to have an index with lists as values but not ok for columns ? |
Python : When using Decimal ( 0 ) and formatting it to .2e format the following happens : However if you just use 0 or 0. the following happens : How come the results are different ? <code> > > > f ' { Decimal ( 0 ) : .2E } '' 0.00E+2 ' > > > f ' { 0. : .2E } '' 0.00E+00 ' | Why is the scientific formatting of Decimal ( 0 ) different from float 0 ? |
Python : I tend to get a LOT of IndentationErrors when writing python code . Sometimes the error will go away when I delete and rewrite the line . Can someone provide a high level explanation of IndentationErrors in python for noob ? Here is an example of a recent indentationError I received while playing CheckIO that ... | Understanding IndentationErrors in Python 2.7 |
Python : I 'm trying to add float values of a vector according to integer values from another vector . for instance if I have : I would like to add the 5 first value of the a vector together ( because the 5 first values of b are 0 ) , the 3 next values together ( because the 3 next values of b are 1 ) and so on.So At t... | Is it possible to combine ( add ) values of a vector according to integer value of another vector |
Python : I have a Panda 's dataframe like the following : And i want to get the countries where its PIB in 2007 was less than in 2002 , but i couldn´t code something to do that only using Pandas built in methods without use python iterations or something like that.The most i 've got is the following line : But i get th... | How to compare data from the same column in a dataframe ( Pandas ) |
Python : Apologies if the question title is too vague - would welcome edits.I 'm trying to parse XML using BeautifulSoup , but because each function call could return None , I have to parse a single element over a number of lines . This gets unwieldy very quickly : Doing the same thing in Swift , a language I 'm far mo... | How can I make string parsing in Python less unwieldy ? |
Python : I 'm working with someone 's Java code where a key data structure is a m x n x p array , float [ ] [ ] [ ] . I need to get it into Python ; currently my approach is to save the array to a text file using Arrays.deepToString and then parse that text file from Python.I am stuck on how to write a regular expressi... | Use Python regex to parse string of floats output by Java Arrays.deepToString |
Python : From my understanding , if a variable of an immutable type is assigned a value equal to another variable of the same immutable type , they should both be referencing the same object . I am using Python 2.7.6 , do n't know if this is a bug.This behaves like I how understood : However , by altering a character ,... | Why is there strange behavior between the IDs of equivalent strings ? |
Python : I am retrieving some content from a website which has several tables with the same number of columns , with pandas read_html . When I read a single link that actually has several tables with the same number of columns , pandas effectively read all the tables as one ( something like a flat/normalized table ) . ... | How to reindex malformed columns retrived from pandas read_html ? |
Python : When I 'm trying to check whether a list is empty or not using python 's not operator it is behaving in a weird manner.I tried using the not operator with a list to check whether it is empty or not.The expected output for not ( a ) == False should be False . <code> > > > a = [ ] > > > not ( a ) True > > > not ... | Weird behaviour of ` not ` operator with python list |
Python : I have a python script that is reading slices from a 3D array , like this : I ca n't help but think there must be a better way of doing this ! Any suggestions ? S <code> def get_from_array ( axis , start , end , array ) : if axis == 0 : slice = array [ start : end , : , : ] elif axis == 1 : slice = array [ : ,... | Python - how can I address an array along a given axis ? |
Python : Please explain below , I think it should have printed True or False since these are boolean expressions . And why it 's printing 2 1 and then 1 2 output : <code> print 1 and 2print 2 and 1print 1 or 2print 2 or 1 2112 | Quirky output python |
Python : I am trying to use mypy to check a Python 3 project . In the example below , I want mypy to flag the construction of the class MyClass as an error , but it doesn't.Can anyone explain this , please ? I.e . explain why mypy does not report an error ? <code> class MyClass : def __init__ ( self , i : int ) - > Non... | Mypy does n't throw an error when mixing booleans with integers |
Python : We know that tuple objects are immutable and thus hashable . We also know that lists are mutable and non-hashable . This can be easily illustrated Now , what is the meaning of hash in this context , if , in order to check for uniqueness ( e.g . when building a set ) , we still have to check each individual ite... | What is the meaning of hash if we still need to check every item ? |
Python : I have such a list with alphanumeric items : I 'm trying to sort it in such an order , using sorted method : but what I get is : I tried passing several keys to sorted , but I ca n't quite figure it out . What key should I use ? Or should I use another method ? <code> [ 'A08 ' , 'A09 ' , 'A02 ' , 'A03 ' , 'A06... | Sort list with alphanumeric items by letter first |
Python : The answer to Javascript regex question Return the part of the regex that matched is `` No , because compilation destroys the relationship between the regex text and the matching logic . `` But Python preserves Match Objects , and re.groups ( ) returns the specific group ( s ) that triggered a match . It shoul... | How to return the regex that matches some text ? |
Python : I 'm using Python 3.8.3 & I got some unexpected output like below when checking id of strings.After the line which adding `` h '' to a , id ( a ) did n't change . How is that possible when strings are immutable ? I got this same output when I use a=a+ '' h '' instead of a+= '' h '' and run this code in a .py f... | Confused why after 2nd evaluation of += operator of immutable string does not change the id in Python3 |
Python : I have a test dataframe : Output : When I call stack on this dataframe , I get this result : Output : How can I prevent stack from sorting the indices so that the order of Group2 remains as A , B , C , All ? <code> df1 = pd.DataFrame ( { `` Group1 '' : [ `` X '' , `` Y '' , `` Y '' , `` X '' , `` Y '' , `` Z '... | How can I prevent stack from sorting indices ? |
Python : I currently have a code that searches for files by keyword . Is there a way to show the number of files found , as the code runs and or show the progress ? I have a large directory to search and would like to see the progress if possible . The code I currently have does n't show much info or processing time . ... | Display number of files found and progress |
Python : I 'm quiet confused to get this with python as below I guess the reason is that in variable a , all three lists ponit to the same memory area until they are used in different ways . Is it right ? Should I always be careful when doing initialization using things like * operator ? THANKS ! <code> > > > a = [ [ ]... | interesting thing about python list initializing |
Python : I have an N-by-2 array of N 2D points , which I want to assign to an M-by-K grid of bins.For instance , points [ m + 0.1 , k ] and [ m + 0.1 , k + 0.9 ] should fall into bin [ m , k ] , where both m and k are integers . It 's possible that a point does n't fall into any of the bins.Implementation-wise , I want... | Python : Faster or Loop-Free Way of Assigning Points to Bins ? |
Python : I am relatively new to python , so I will try my best to explain what I am trying to do . I am trying to iterate through two lists of stars ( which both contain record arrays ) , trying to match stars by their coordinates with a tolerance ( in this case Ra and Dec , which are both indices within the record arr... | Preventing multiple matches in list iteration |
Python : I need a web socket client server exchange between Python and JavaScript on an air-gapped network , so I 'm limited to what I can read and type up ( believe me I 'd love to be able to run pip install websockets ) . Here 's a bare-bones RFC 6455 WebSocket client-server relationship between Python and JavaScript... | Why does client.recv ( 1024 ) return an empty byte literal in this bare-bones WebSocket Server implementation ? |
Python : Let 's assume we have the following dataframe that includes customer orders ( order_id ) and the products that the individual order contained ( product_id ) : It would be interesting to know how often product pairs appeared together in the same basket.How does one create a co-occurence matrix in python that lo... | How to create a co-occurence matrix of product orders in python ? |
Python : Given a dataframe df , ( real life is a +1000 row df ) . Elements of ColB are lists of lists.How can efficiently create a ColC that is a string using the elements in the different columns , like this : I tried with df.apply along these lines , inspired by this : This works for the first 2 elements of the strin... | How to create strings from dataframe columns elements in Python ? |
Python : ProblemI need to reduce the length of a DataFrame to some externally defined integer ( could be two rows , 10,000 rows , etc. , but will always be a reduction in overall length ) , but I also want to keep the resulting DataFrame representative of the original . The original DataFrame ( we 'll call it df ) has ... | Unexpected number of bins in Pandas DataFrame resample |
Python : I need to check if a point lies inside a bounding cuboid . The number of cuboids is very large ( ~4M ) . The code I come up with is : It takes 8 seconds to run np.all and 3 seconds to run np.nonzero on my computer . Any idea to speed up the code ? <code> import numpy as np # set the numbers of points and cuboi... | How to speed up numpy.all and numpy.nonzero ( ) ? |
Python : I am working with a pandas dataframe . I am trying to split a column after the date and time from the rest of the string.Desired output : If I try something like df [ `` data '' ] .str.extract ( '^ ( .* ? [ 0-9 ] { 2 } ) ( . * ) $ ' ) it just strips everything after the 22 ( day ) <code> df data0 Oct 22 12:56:... | Pandas split after month day time from rest of string |
Python : I have 2 lists which i have created and added an incrementing value to each item . The reason being that the values in each list are to be joined together in a dictionary . However the values in each list are not a 1 to 1 pair..this is why i added the incrementing values to assist with associating each key wit... | Python- add to dictionary based on an incrementing value in 2 lists |
Python : Simple question : So it seems that if I assign a dictionary literal with a duplicate key to a variable it is the second key/pair that is used , at least for this particular python version.Is this behaviour guaranteed ? <code> Python 2.6.6 ( r266:84292 , Aug 9 2016 , 06:11:56 ) [ GCC 4.4.7 20120313 ( Red Hat 4.... | Assigning python dictionary literals : are the semantics guaranteed ? |
Python : I have the following code in Python:1.For times = 1000000 I get the results : generator : 0.107323884964list : 0.2254931926732.For times = 10000000 I get : generator : 0.856524944305list : 1.83883309364I understand why the 2nd list would take more time to create but why would the 2nd generator take more time a... | Python Generator that yields more results takes more time to create |
Python : I am going through this link to understand Multi-channel CNN Model for Text Classification.The code is based on this tutorial.I have understood most of the things , however I ca n't understand how Keras defines the output shapes of certain layers.Here is the code : define a model with three input channels for ... | Understanding shapes of Keras layers |
Python : I want to count the number of duplicated tuples in a list.For example num_list:I want to return the result : Total duplicates : 1which is the ( 2 , 8 ) pair.what i have so far is not very efficient , so I am wondering if there 's a more efficient way to do this ? <code> num_list = [ ( 3,14 ) , ( 2,8 ) , ( 10,2... | Count the number of duplicate tuples inside a list |
Python : I have a and the Output should be `` five '' is the first element because in list1 has the highest number of occurrences ( 3 ) '' two '' is the second element because in list1 has the next highest number of occurrences ( 2 ) '' one '' , `` three '' and `` six '' have the same lower number of occurrences ( 1 ) ... | How to sort a list with duplicate items by the biggest number of duplicate occurrences - Python |
Python : I came up with this Python code for the trial division variant of the `` Sieve of Eratosthenes '' : It does n't work as I expected.When debugging it I get some behavior I do n't understand when filter gets called : the x parameter of the lambda gets a concrete argument which is the next element from the picker... | Troublesome filter behavior when implementing the `` Sieve of Eratosthenes '' in python |
Python : I 've spent the last 2 hours on this and I 've probably read every question on here relating to variables being passed to functions . My issue is the common one of the parameter/argument being affected by changes made inside the function , even though I have removed the reference/alias by using variable_cloned... | Passed argument/parameter in function is still being changed after removing the reference/alias |
Python : I want to add a new column , Category , in each of my 8 similar dataframes.The values in this column are the same , they are also the df name , like df1_p8 in this example.I have used : Ultimately , I want to append/concat these 8 dataframes into one dataframe.I wonder if there is more efficient way to do it ,... | More efficient way to add columns with same string values in multiple dataframes with loops or lambdas ? |
Python : I 'm trying to link multiple rows from a DataFrame in order to get all possible paths formed by connecting receiver ids to sender ids.Here is an example of my DataFrame : created with : Result of my code should be list of chained ids and the total amount for the transaction chain . For the first two rows in th... | Summing a transaction chain in a dataframe , rows linked by column values |
Python : I would like to create a game in python but I need a thought provoking impulse , how I can draw a point , which draws a line behind him/a trail , so far , so good , I have no idea how to make my point not just moving in the 4 directions , I want him to move forward on his own and the user should steer left and... | Python point curves |
Python : So , lets say I have this code : As seen in the comment , if the print statement is uncommented , the code works normally , and the signal handler will catch any subsequent CTRL-C presses like it should . However , if left commented , another signal will never be caught.Why is this ? My guess is that consecuti... | python - Catching signals between sleep calls |
Python : I was recently surprised to find that the `` splat '' ( unary * ) operator always captures slices as a list during item unpacking , even when the sequence being unpacked has another type : Compare to how this assignment would be written without unpacking : It is also inconsistent with how the splat operator be... | Is there a way to splat-assign as tuple instead of list when unpacking ? |
Python : I am making a little wrapper module for a public library , the library has a lot of repetition , where after object creation , maybe methods require the same data elements . I have to pass the same data in my wrapper class , but do n't really want to pass the same thing over and over . So I would like to store... | decorating a method in python |
Python : I defined the following Enum in Python : I would expect thatwill returnHowever , what I get is quite confusingWhy is it so ? <code> class Unit ( Enum ) : GRAM = ( `` g '' ) KILOGRAM = ( `` kg '' , GRAM , 1000.0 ) def __init__ ( self , symbol , base_unit = None , multiplier = 1.0 ) : self.symbol = symbol self.m... | Referring Enum members to each other |
Python : I am trying to turn information on a picture of 13 colourful blocks into some texts . For example , I need to know how many yellow and blue blocks here , and their sequence . `` c : \target.jpg '' `` c : \blue.jpg '' '' c : \yellow.jpg '' What I have is : When I run them separately , it gives results like thes... | Arranging sequences in 2 combined arrays using Python |
Python : I am trying to do the following logic in a join_key . date + book + bdr + COALECSE ( cusip , isin , deal , id ) I am trying to use : Also tried : For some reason this code isnt picking up Id as part of the key.For example in the 2nd row I should get 20191031|15|ITOR|8011898573.Also if it helps it comes from a ... | Pandas , fillna/bfill to concat and coalesce fields |
Python : I am trying to make a word guessing game . Everything works except for the last if statement part . If the user guesses the name correctly , it does n't print `` Won ! '' . However , if not , else statement executes and it does print `` Lost ! '' . Why is that ? I checked it many times , but I coulnd't find an... | Why does n't this if statement execute ? |
Python : I am trying to write a blackjack code in python 2.7 and ca n't figure out how to sum my c1 and c2 once an output is given . This is what I have so far : output : *The current syntax return the wrong sum is being calculated . The sum should be 16 . Could someone please provide guidance ? Thank you <code> def bl... | summing string and integers in list in python |
Python : I am just starting to play with OpenCV and I have found some very strange behaviour from the contourArea function.See this image.It has three non connected areas , the left is a grouping of long strokes and on the top center there is a single dot and finally a big square on the right.When I run my function , I... | Open CV Contour area miscalculation |
Python : I have a NumPy r by c matrix of zeroes and ones . And I have a list of c words . I want to return a list of length r where each element is a space delimited string made up of only those words that match 1 's in that matrix 's row . Here 's an example : What is a Pythonic way to accomplish this ? Thanks , G <co... | From matrix to list of words |
Python : I 'm learning numpy . But I got some questions confused me : and : sum ( a ) give the same result.So why a built-in function can support the calculation of a data type from a third-party library ? min ( ) and max ( ) do the same . ( When the dim is 1 ) I got two guesses about this , I prefer the latter : pytho... | Why python bulit-in functions such as sum ( ) , max ( ) , min ( ) can be used to calculate the numpy 's datatype ndarray ? |
Python : I have data in following format : I would like to fill data in second column to match row that has same first column and non null value in second . So I would get following : How can it be achieved ? <code> 8A564 nan json8A928 nan json8A563 nan json8A564 10616280 json8A563 10616222 json8A564 nan json8B1BB 1098... | Filling cell based on existing cells |
Python : I , a beginner , am working on a simple card-based GUI . written in Python . There is a base class that , among other things , consists a vocabulary of all the cards , like _cards = { 'card1_ID ' : card1 , 'card2_ID ' : card2 } . The cards on the GUI are referenced by their unique IDs . As I plan to make the c... | Catching the same expection in every method of a class |
Python : I have a voting dataset like that : but they are both string so I want to change them to integer matrix and make statistichou_dat = pd.read_csv ( `` house.data '' , header=None ) however , it shows error , how to solve it ? : <code> republican , n , y , n , y , y , y , n , n , n , y , ? , y , y , y , n , yrepu... | how to change string matrix to a integer matrix |
Python : I am trying to predict the trend of an internet post.I have available the number of comments and votes the post has after 2 minutes of being posted ( can change , but it should be enough ) .Currently I use this formula : And then I find k experimentally . I get the post data , wait an hour , do And so on . Thi... | Implementing a machine learning-like optimizer |
Python : I have a series of functions that serve to classify data . Each function is passed the same input . The goal of this system is to be able to drop in new classification functions at will without having to adjust anything.To do this , I make use of a classes_in_module function lifted from here . Then , every cla... | Fudging the line between classes and functions |
Python : In R , ! is really an infix operator ` ! ` , so statements likeare totally valid . Is there a way to access the first order object underlying not in Python ? I have been googling with no success . <code> Map ( ` ! ` , c ( T , F , F ) ) | What is python 's not ? A special function type ? |
Python : Here is my sample data : Here is my desired output : I have created a new column called 'HP ' where I want to extract the horsepower figure from the original column ( 'Engine Information ' ) Here is the code I have tried to do this : The idea is I want to regex match the pattern : ' a sequence of numbers that ... | Regular expression to find a sequence of numbers before multiple patterns , into a new column ( Python , Pandas ) |
Python : Suppose I have a timeseries of values called X.And I now want to know the first index after which the values of some other series Y will be reached by X . Or put differently , for each index i I want to know the first index j after which the line formed by X from j-1 to j intersects the value of Y at i.Below i... | How do I find the index at which a given value will be reached/cross by another series ? |
Python : I need to know if I can easily assign a variable within my script from a declaration in a text file . Basically , I want the user to be able to change the variable via the text file to match the numbers needed without having to fiddle with the source code.Text file input format : I simply want to load this int... | Importing a 3-D list variable from a text file in Python |
Python : Consider the following code : Is this a good idea , bad idea or should I just destroy myself ? If you 're wondering why I would want this , I got a function repeating itself every 4 seconds , using win32com.client.Dispatch ( ) it uses the windows COM to connect to an application . I think it 's unnecessary to ... | Assigning a variable directly to a function in Python |
Python : I have a pandas dataframe like this : I want to have only the top 3 characters in the dataframe and the remaining are combined as others so table become : How can I achieve this ? Thank you . <code> character count0 a 1041 b 302 c 2103 d 404 e 1895 f 206 g 10 character count0 c 2101 e 1892 a 1043 others 100 | Combining rows to 'others ' in pandas |
Python : I am trying to create a program that cycles through a string , This is what i have so far.This just gives me and so on till the last letter.This kind of does what i want but not fully.What i want this program to do is to print something like this.and so on ... .cycling thorugh the string , but i cant quite get... | Python - Cycing through a string |
Python : In strongly typed languages such as Java , there is no need to explicitly check the type of object returned since the code can not compile if the return types do not match method signature . Ex . You can not return a boolean when an integer is expected.In loosely typed languages such as Ruby , JavaScript , Pyt... | In unit testing loosely typed languages , should the return type of methods be checked ? |
Python : I need to handle signals in my code and I am using global to share state between functions : Is there a way to avoid global variable in this case ? What is the best way to share state in this case ? <code> exit = Falsedef setup_handler ( ) : signal.signal ( signal.SIGTERM , handler ) def handler ( num , frame ... | What is Pythonic way to share state inside one module ? |
Python : Say I have the following dataframe df : And you want to check if , between columns A , B , and C , there is a common word , and create a column D with 1 if there is and 0 if there is n't any . For a word to be common , it 's enough for it to appear in just two of the three columns.The outcome should be : I am ... | Python : determine if three text strings stored in a dataframe have any words in common |
Python : I 'm trying to create a set of test cases for a project I 'm working on , and I 'd like to create all possible test cases and iterate through them ( quick program , should n't take long ) . The test cases should all be a list of length 1-4 and each item on the list should be an integer between 0-10 , inclusive... | How to create list of all possible lists with n elements consisting of integers between 1 and 10 ? |
Python : I have some acceleration data for which I am trying to count the length of sequences given a set of conditions . In this case I want to count the length of a sequence when the acceleration moves > 2.78 and then drops back below 0.An example would beThe return result here would be a count of 7 ( 2.88 , 2.86 , 2... | Length ( count ) of sequences with start and end condition Python |
Python : If I have a this evaluates to True : but this evaluates to False : as doesWhy ? I found that getattr ( a , 'foo ' ) and a.foo both are represented by So no hint there ... . <code> class A : def foo ( self ) : pass getattr ( A , 'foo ' ) is A.foo a = A ( ) getattr ( a , 'foo ' ) is a.foo a.foo is a.foo < bound ... | Why does ` instance_of_object.foo is instance_of_object.foo ` evaluate False ? |
Python : Suppose I have the following , which is the better , faster , more Pythonic methodand why ? or : <code> if x == 2 or x == 3 or x == 4 : do following ... if x in ( 2 , 3 , 4 ) : do following ... | Should I use 'in ' or 'or ' in an if statement in Python 3.x to check a variable against multiple values ? |
Python : If I run the following code in a Python interpreter : Why is the result False ? <code> > > > object.__dict__ is object.__dict__False | Why is `` object.__dict__ is object.__dict__ '' False ? |
Python : I 'm creating a script that 's actually an environment for other users to write code on . I 've declared several methods in a class and instantiate an object so users can use those methods as simple interpreter functions , like so : Since I do n't want the user to call the methods with fw.method1 ( arg ) , I s... | How to alias all methods from an object ? |
Python : I just encountered the following and am curious about Python 's behavior : In particular , why does ( 1 in range ( 2 ) ) == True evaluate True and l in range ( 2 ) == True evaluate to False ? It seems like there is some strange order of evaluation behavior in the latter , except that if you make the order expl... | Order of evaluation when testing equivalence of booleans |
Python : The input is a sorted list of elements and an external item . For example : What is the fastest way of finding out which two elements in list_ item falls between ? In this case for example , the two numbers would be 3.5 and 5.8 . Any ideas ? <code> list_ = [ 0 , 3.5 , 5.8 , 6.2 , 88 ] item = 4.4 | Fastest way to find which two elements of a list another item is closest to in python |
Python : Given a string s representing characters typed into an editor , with `` - > '' representing a delete , return the current state of the editor.For every one `` - > '' it should delete one char . If there are two `` - > '' i.e `` - > - > '' it should delete 2 char post the symbol.Example 1ExplanationThe `` b '' ... | how to delete char after - > without using a regular expression |
Python : This is from Leetcode 804 : Unique Morse Code Words . I am wondering why my code gives the right Morse code but it is sorted in alphabetic order which is not on purpose . Any contribution is appreciated.Input : code : output : <code> words = [ `` gin '' , `` zen '' , `` gig '' , `` msg '' ] class Solution : de... | Why is string sorted in alphabetic order ? |
Python : I have a sorted list of integers and I find want find to the number runs in this list . I have seen many examples when looking for numbers runs that increment by 1 , but I also want to look for number runs where the difference between numbers is customizable.For example , say I have the following list of numbe... | Find number runs with customizable distance between numbers |
Python : map and filter are often interchangeable with list comprehensions , but reduce is not so easily swapped out as map and filter ( and besides , in some cases I still prefer the functional syntax anyway ) . When you need to operate on the arguments themselves , though , I find myself going through syntactical gym... | Can you apply an operation directly to arguments within map/reduce/filter ? |
Python : Please help in troubleshooting python3 logging from multiple processes into same log file.i have dameon main script , which runs in back ground , and calls few other pythons scripts every 15seconds , and each python script is written with same TimedRotatingFileHandler attributes , and all logs are written into... | python3 : timedrotatingfilehandler log rotation issue with same log file with multiple scripts |
Python : I have a matrix named xs : Now I want to replace the zeros by the nearest previous element in the same row ( Assuming that the first column must be nonzero. ) . The rough solution as following : Any help will be greatly appreciated . <code> array ( [ [ 1 , 1 , 1 , 1 , 1 , 0 , 1 , 0 , 0 , 2 , 1 ] , [ 2 , 1 , 0 ... | Is there some elegant way to manipulate my ndarray |
Python : I have a below dataframe I would like to create a new column `` check '' that would be based on data in previous rows in dataframe : Find cell in action column = `` DONE '' Search for the first CREATED or UPDATED with the same id in previous rows , before DONE . In case its CREATED then put C in case UPDATED p... | pandas dataframe column based on previous rows |
Python : I want to fill a matrix from an array of indices : The result is : As desired.QuestionIs there a way to do this in pure python/numpy without looping ? <code> import numpy as npindx = [ [ 0,1,2 ] , [ 1,2,4 ] , [ 0,1,3 ] , [ 2,3,4 ] , [ 0,3,4 ] ] x = np.zeros ( ( 5,5 ) ) for i in range ( 5 ) : x [ i , indx [ i ]... | Fill a matrix from a matrix of indices |
Python : I have a dataset as follow : For each string I want to get the positions of first element and last element of each `` Uninterrupted S groups '' . For example , for first row I have 'DDDSSDSSDS ' ( as you see I have three groups of S ) and my favorite output for this `` S group '' s is something like [ ( 3,5 ) ... | How to apply regex over all the rows of a dataset ? |
Python : Assume yo = Yo ( ) is a big object with a method double , which returns its parameter multiplied by 2.If I pass yo.double to imap of multiprocessing , then it is incredibly slow , because every function call creates a copy of yo I think.Ie , this is very slow : Output : ... BUT , if I wrap yo.double with a fun... | Passing a method of a big object to imap : 1000-fold speed-up by wrapping the method |
Python : I am trying to understand a piece of Python code.First , I have the following file structure : The __init__.py in the folder folder1 has nothing.The __init__.py in the folder model has the following : With that said , I have some code in python that uses all the aboveNow , I am trying to understand the followi... | Trying to understand __init__.py combined with getattr |
Python : I am subclassing a type defined in a C module to alias some attributes and methods so that my script works in different contexts . How is it that to get this to work , I have to tweak the dictionary of my class manually ? If I do n't add a reference to DistanceTo in the dictionnary , I get Point3d has no attri... | Method ignored when subclassing a type defined in a C module |
Python : After having tried many things , I thought it would be good to ask on SO . My problem is fairly simple : how can I solve the following equation using Sympy ? EquationI want to solve this for lambda_0 and q is an array of size J containing elments between 0 and 1 that sum op to 1 ( discrete probability distribu... | Solve equation with sum and index using Sympy |
Python : I have a list : I want to swap 12 and 89 such that the list should lookWhen I do it this wayNothing is changedBut when I do it this wayIt works perfectSo why it is n't working the first way ? PS-The whole reason I want to do the first way is because I want to find the max element in a list and then swap it wit... | Swaping two elements in a list shows unexpected behaviour |
Python : I have a node system where every node only stores its inputs and outputs , but not its index . Here is a simplified example : Now I want to order that nodes , so that all inputs are already processed when processing that node . For this simple example , a possible order would be [ Node1 , Node2 , Node3 , Node4... | Sort nodes based on inputs / outputs |
Python : im new to python and trying to one hot encode . My code is below : I am trying to one hot encode the service subcodes ( ssc ) associated to each ID . where lets say id 1895650 has two ssc 's 2,4 then the encoding should be 0101 . But as you see in my code the output shows as 0101000 for some reason . I do not ... | Strange Hot encoding issue with function in Python |
Python : I have two pieces of code that seem to do the same thing but one is almost a thousand times faster than the other one.This is the first piece : In ts I have values like : In contrast , this part of the code : Creates ts populated with the values like : I can not figure out what the essential difference is betw... | Why is changing values in a column of a pandas data frame fast in one case and slow in another one ? |
Python : From the code here : https : //www.learnsteps.com/increasing-performance-python-code/which produces this output : Can someone provide a better explanation than 'function lookups are costly ' as to why creating a function prototype close to the use of the function is somehow faster ? ( This does n't work for mo... | Python : Why does copying the function name to a local namespace result in a faster access |
Python : Still new to python and coding , only about 6 weeks into this adventure . I started a finance project to try and figure out what % of the portfolio should be in cash , and how much should be invested based on the current market performance . No idea if this research will have any relevance but it has been help... | Looking for some guidance on combinatorics in python |
Python : Given the DataFrame generated by : df : I need to , for each id , remove rows which are more than 24hours ( 1 day ) from the latest time_entered , for that id . My current solution : which gives the correct , expected , output : However , my real data is tens of millions of rows , and hundreds of thousands of ... | Efficient way of filtering by datetime in groupby |
Python : I have the following trees ( tree_1 , tree_2 , tree_3 ) stored in a dictionary ( dict_1 , dict_2 , dict_3 ) . How can I recursively traverse all the paths of the tree , collecting all the nodes from the root to the last node of each branch ? In other words , I would like to generate a list of all the possible ... | Problems while traversing and extracting the nodes of a tree ? |
Python : I have a dataframe belowand it is like this : There are some consecutive duplicated values ( ignore the Date value ) within each 'ID ' ( Name ) , e.g . line 1 and 2 for James , the From_num are both 420 , same as line 9 and 10 , I wish to drop the 2nd duplicated row and keep the first . I wrote loop conditions... | Pandas drop consecutive duplicate rows only , ignoring specific columns |
Python : I 'm new to python , and I have a simple question.say I make a subclass of str to change everything into 'test ' : all I want is 'test ' , but where does python store the original value '12345 ' ? I can not find it anywhere.after checking this , I actually find it in getnewargsthen I change this to : why is 12... | where does python store origin value for str |
Python : I have a list of variables , and a function object and I would like to assign the correct number of variable depending on the function.so if f = sum2 , I would like it to call first 2 elements of varList , and if f = sum3 , to call it with 3 elements of the function . <code> def sum2 ( x , y ) : return x + yde... | python - enter the correct number of variables based on function handle |
Python : Here is MRE : What I am trying to do is loop through each dictionary and append each value to a column in a dataframe.right now I am doingoutputting : Yes this is what I want however I have over 1M dictionaries in a list . Is it most efficient way ? EDIT : pd.DataFrame ( data ) .rename ( columns= { ' 1 ' : 'co... | Efficient way of looping through list of dictionaries and appending items into column in dataframe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.