text
stringlengths
46
37.3k
title
stringlengths
12
162
Python : I have the following code in python ( numpy array or scipy.sparse.matrices ) , it works : But it does n't look elegant . ' a ' and ' b ' are 1-D boolean mask . ' a ' has the same length as X.shape [ 0 ] and ' b ' has the same length as X.shape [ 1 ] I tried X [ a , b ] but it does n't work.What I am trying to ...
Shorter version of this numpy array indexing
Python : I 've created a list ( which is sorted ) : I want to extract the numbers from this list that are at least five away from each other and input them into another list . This is kind of confusing . This is an example of how I want the output : As you can see , none of the numbers are within 5 of each other.I 've ...
extracting numbers from list
Python : I am reading a snippet of Python code and there is one thing I ca n't understand . a is a list , num is an integerworks but wo n't work . Can anyone explain this to me ? <code> a += num , a += num
What 's the difference between a += number and a += number , ( with a trailing comma ) when a is a list ?
Python : I had been using [ 0-9 ] { 9,12 } all along to signify that the numeric string has a length of 9 or 12 characters . However I now realized that it will match input strings of length 10 or 11 as well . So I came out with the naive : Is there a more succinct regex to represent this ? <code> ( [ 0-9 ] { 9 } | [ 0...
Is the better way to match two different repetitions of the same character class in a regex ?
Python : Summary Question : Why does Heroku indicate os.system ( 'say ... ' ) is `` not found '' and how can I fix it ? I have a Node.js app where I am using child_process to spawn a Python script that reads out audio when it 's given a specific word . I know that it works when I run my server on localhost:5000 , but w...
Spawning python script in nodejs on heroku
Python : I want to return a list with the interleaved elements of two lists directly from the list comprehension - without use a next step to flaten the result . Is it possible ? Return [ [ 1 , 3 ] , [ 4 , 7 ] , [ 2 , 4 ] ] But how can I get directly from the list-comprehension [ 1 , 3 , 4 , 7 , 2 , 4 ] ? <code> alist1...
Get a list ( without nested list ) directly from a list comprehension
Python : my .py file isand xml file isi got this LINE 1 : ... partner '' . `` picking_warn_msg '' as `` picking_warn_msg '' , '' res_partn ... as error message and i ca n't move forward with my project 'odoo ' is not running at all <code> class Suppiler ( models.Model ) : _inherit = `` res.partner '' author= fields.Boo...
I got this `` LINE 1 : ... partner '' . `` picking_warn_msg '' as `` picking_warn_msg '' , '' res_partn ... '' error while inherit res.partner
Python : Two DataFrames have matching values stored in their corresponding 'names ' and 'flights ' columns.While the first DataFrame stores the distances the other stores the dates : distancesDF : datesDF : I would like to merge them into single Dataframe in a such a way that the matching entities are synced with the c...
How to merge two DataFrames into single matching the column values
Python : I have some Python classes that , if simplified , look like : The base class contains methods ( represented above by doThings and doMoreThings ) which implement functionality common to both the foo and bar subclasses . The foo and bar subclasses differ essentially in how they interpret the value field . ( Abov...
Python - typechecking OK when error would n't be thrown otherwise ?
Python : I wanted to see if shlex was a good choice for something I 'm trying to build , so I thought I 'd put it in debug mode to play around with it . Only , shlex 's constructor has this weird thing it does : it sets self.debug to 0 and then immediately checks if it 's true.I know Python has some powerful metaprogra...
Putting shlex in debug mode
Python : A while back , I was working on a programming problem ( CCC ) . I have also come across similar questions in past contests so I decided to ask about this one . The problem is basically this . You are given n people and p pieces of pie.n people are standing in a row.You must distribute p pieces of pie amongst t...
Converting simple recursive method which recurses within a loop into iterative method
Python : We have a dictionary d1 and a condition cond . We want d1 to contain only the values that satisfy the condition cond . One way to do it is : But , this creates a new dictionary , which may be very memory-inefficient if d1 is large.Another option is : But , this modifies the dictionary while it is iterated upon...
Efficiently filtering a dictionary in-place
Python : Consider the following instance behavior in Python.The Python snippet below prints Should n't it print Why would an element in a list by successfully overwritten , but not the entire list object ? <code> def change ( elements ) : elements [ 0 ] = 888 elements = [ -3 , -1 , -2 , -3 , -4 ] print ( elements [ 0 ]...
Python instance behavior with lists
Python : I have a scalar function f ( a , b , c , d ) that has the following permutational symmetryf ( a , b , c , d ) = f ( c , d , a , b ) = -f ( b , a , d , c ) = -f ( d , c , b , a ) I 'm using it to fully populate a 4D array . This code ( using python/NumPy ) below works : But obviously I 'd like to exploit symmet...
How to exploit permutational symmetry in this loop ?
Python : I would like to know if the rows selected by : are the same as the rows selected by : In this case the order of the rows does n't matter.Is there any case in which groupby does not fulfill the commutative property ? <code> groupby ( [ ' a ' , ' b ' ] ) groupby ( [ ' b ' , ' a ' ] )
Is groupby from pandas commutative ?
Python : I have a pandas dataframe of the following structure : I want to remove duplicate rows where ID and Val1 are duplicates , and where Val2 sums to zero across two rows . The positive/negative Val2 rows may not be consecutive either , even under a groupbyIn the above sample data , rows 0 and 1 , as well as 7 , 8 ...
Deleting rows which sum to zero in 1 column but are otherwise duplicates in pandas
Python : I have seen many online examples with different ways of importing modules . I was wondering what the difference is , if it is in speed , accuracy , priority , or psychology.The first , and most common is ; I understand the methodry , but this seems unnecessary when you can use , like I personally do ; Less lin...
What is the difference between these import statements ?
Python : I 've hit a wall with a data analysis project I 'm working on . Essentially , if I have example CSV ' A ' : And I have example CSV ' B ' : If I perform a merge using Pandas , it ends up like this : How could I instead make it become : This is my code : I would really appreciate any help - I 'm very stuck ! And...
Prevent duplication of rows when performing merge
Python : I want to do a multiple queries . Here is my data frame : I have 3 queries : Group A or BMath > EngName starts with ' B ' I tried to do it one by oneThen , I tried to merge those queriesI also tried to pass str.startswith ( ) into df.query ( ) I have tried lots of ways but no one works . How can I put those qu...
How to do multiple queries ?
Python : I 'm facing strange error right now , I have python script , that is sending/receiving data using TCP socket , everything works fine , but when I 'm trying to download image with this script , it will download it , but there is a missing one-pixel row . Any ideas on how to fix it ? Server download script : Cli...
Missing one-pixel row while transfering image with TCP socket
Python : I am looking for a way to dynamically create classes with specific properties accessible via typical instance notation.Details of how the `` props '' are actually acquired and modified would be hidden.This also makes it easier to add access to new props as they become available.I have experimented with techniq...
creating class properties dynamically
Python : I 'm trying to export a list of strings to csv using comma as a separator . Each of the fields may contain a comma . What I obtain after writing to a csv file is that every comma is treated as a separator.My question is : is it possible to ignore the commas ( as separators ) in each field ? Here is what I 'm t...
Python write to csv with comas in each field
Python : Currently I have the following lists : What I am trying to do is to replace the characters in the instruments list with the characters from the score list ( excluding the | ) .I am currently experiencing the following issuesThe characters are being replaced row by row , rather than column by column . Instrumen...
Replace characters in a list by column rather than by row
Python : Say I have a list of class objects in Python ( A , B , C ) and I want to inherit from all of them when building class D , such as : Unfortunately I get a syntax error when I do this . How else can I accomplish it , other than by writing class D ( A , B , C ) ? ( There are more than three classes in my actual s...
Inheriting from classes unpacked from a list
Python : I know that I can split a list into sub-lists of equal size using : However I 'm not sure how to split a list of length k^m into sub-lists , then further sub-lists until each sub-list has length of 1.For example : Whenever I 've tried to loop this I get tied in knots , is there a short-cut ? <code> segment = l...
How to split sub-lists into sub-lists k times ? ( Python )
Python : I 'm trying to do some calculations in my python script but i 'm getting some weird results . For example : If I upscale the numbers I get the expected results : I 'm pretty sure that the answer for the first code snippet should be 3.0 and not 2.0 . Can someone explain me why this is happening and how to fix i...
Floor division with small numbers returning wrong answer
Python : I see that one could have several versions of a Python package installed : How might I check which version of a package ( i.e . which file , not which version number ) an application is using ? Ignoring the obvious `` Zim will use the package at /usr/lib/pymodules/python2.7/zim/signals.py '' is there way to se...
Which package is Python using ?
Python : I stumbled upon some strange behaviour using ipython-notebook and wondered what , if any , the purpose was . If you enter a semicolon before a function call , you get the result of applying the function to a string which reflects all the code after the function name . For example , if I do ; list ( 'ab ' ) I g...
Weird behaviour with semicolon before function call in ipython/ipython notebook
Python : Say I have a listand I want to sum each item in the list with every other item in the list . I could do this : Is assigning two variables ( a and b ) to items in the same list ( l ) the best way to access and perform operations on those items ? Is there a better way to do this ? I 've looked at list methods an...
Is assigning two variables to items in the same list the best way to access and perform operations on those items ?
Python : Notes on Decimal says : I do n't understand why Decimal ( ' 3.14 ' ) + 2.71828 is undefined . Decimal can be constructed from a float so I think that __add__ can be implemented as follows : With it we will be able to get Decimal ( ' 3.14 ' ) + 2.71828 = Decimal ( ' 3.14 ' ) + Decimal ( 2.71828 ) = 5.8582800000...
Why decimals do not interoperate with floats
Python : Suppose I have the following set : I would like to find out if either foo or bar exists in the set . I 've tried : This works , but is there not a more Pythonic way of doing this check without having multiple or statements ? I ca n't find anything in the standard Python set operations that can achieve this . U...
Check for any values in set
Python : Using the below as an example , we can see x.giveMyNum ( ) will be called 4 times - 3 times to check the value of myNum and once to construct the list to return . You 'd probably want it to be called only 3 times , as it 's a pure function and its value wo n't change.List Comprehension Version : I know you can...
Preventing multiple calls in list comprehension
Python : I want to split a string using - , += , == , = , + , and white-space as delimiters . I want to keep the delimiter unless it is white-space.I 've tried to achieve this with the following code : I expected the output to beHowever I gotWhich is almost what I wanted , except that there are quite a few extraneous N...
Python regex -- extraneous matchings
Python : I am trying to do a cross tab based on one column where a third column matches . Take the example data : where id_match matches i want to find the resulting sum of of the time for the cross tab of the demographic column . The output would look like this : Hopefully that makes sense , comment if not . Thanks J ...
Cross tab on one column where third column is matched
Python : I 'm trying to make a function that will always return me a pre-fixed number of elements from an array which will be larger than the pre-fixed number : where i stands for index of array to fetch and arr represent the array of all elements : Example : where i = 9 and the array return the [ 9:11 ] + [ 0:7 ] to c...
Python how cyclic fetch a pre-fixed number of elements in array
Python : So I ’ m trying to write a Python 3 function for a challenge that takes in a string , removes the vowels and returns it without the vowels . I wrote the below code but it seems to only take out the vowels partially while leaving some untouched . <code> def remove_vowels ( string ) : vowels = [ ' a ' , ' e ' , ...
Why is my function partially doing what it ’ s supposed to do ?
Python : Look at this Python code : It prints False . That 's weird by itself , but becomes much weirder when you consider the following : If x is a number ( int , float , complex , Fraction , Decimal ) instead of a string , it still prints False . For bytes and bytearray , too . But for every other type ( hashable if ...
Strings not referenced by dicts ?
Python : I 've been tasked with creating a dictionary whose keys are elements found in a string and whose values count the number of occurrences per value.Ex . I have the for-loop logic behind it here : This does exactly what I want it to do , except with lists instead of dictionaries . How can I make it so counter bec...
Nested for-loops and dictionaries in finding value occurrence in string
Python : I 'm developing a grid based game in pygame , and want the window to be resizable . I accomplish this with the following init code : As well as the following in my event handler : The problem I 'm having is that it seems a pygame.VIDEORESIZE event is only pushed once the user is done resizing the window , i.e ...
Update during resize in Pygame
Python : How do I use numpy / python array routines to do this ? E.g . If I have array [ [ 1,2,3,4 , ] ] , the output should be Thus , the output is array of double the row and column dimensions . And each element from original array is repeated three times . What I have so far is thisThis gives me array for the inputT...
How to replace each array element by 4 copies in Python ?
Python : I 'm looping over a heavily nested dictionary of lists ( system information ) and storing the complete path to keys in this format : Next , the complete paths are read in and will be compared to the system information ( Data ) . How can I convert the complete path to this format ? I can do something like : How...
Python store dictionary path and read back in
Python : I know I can attach a function to a class and make it a method : To my surprise this works also with a bound method from one class to another : Can I safely use this ? Is there something I am overseeing ? updateOne caveat that I found already : Even though I called the method from B , It seems bound to Foo.And...
Safely bind method from one class to another class in Python
Python : I have this plot : The values range from 0 to 1 , but the colorbar extends above 1 and below 0 . I want the colorbar to NOT show values out of the [ 0 , 1 ] range . How can this be done ? My code : <code> import numpy as npimport plotly.graph_objects as gofig = go.Figure ( ) fig.add_trace ( go.Contour ( z=np.r...
Colorbar does n't respect limit values
Python : A bit of background : I have a Raspberry Pi 3b running Raspbian ( Debian ) 9.11 . This original Pi runs a Python 3 script that captures text input from a handheld scanner and sends it into a MySQL database , and then plays a wav file so the employees scanning know it was successful . I daemonized this process ...
Pygame wo n't play audio , but only when running as a daemon
Python : I want to preface this by saying that I know the difference between == and is one is for references and the other is for objects . I also know that python caches the integers in the range ( -5 , 256 ) at startup so they should work when comparing them with is . However I have seen a strange behaviour.This is t...
Python 3.6.5 `` is '' and `` == '' for integers beyond caching interval
Python : I 'm getting started to AsyncIO and AioHTTP , and i 'm writing some basic code to get familiar with the syntax . I tried the following code that should perform 3 requests concurrently : Here is the output : I do n't understand why do i get that error , can anyone help me on this ? <code> import timeimport logg...
Asyncio event loop is closed when using asyncio.run ( )
Python : Here I am trying to get data from arduino but it is coming in the format b'29.20\r\n ' . I want to have the data in the format `` 29.20 '' so I can plot it.I tried ardstr = str ( ardstr ) .strip ( '\r\n ' ) and ardstr.decode ( 'UTF-8 ' ) but none of them is working . My python version is 3.4.3.What can I do to...
How to convert the byte class object into a string object
Python : I am working with python and I am trying to find powers of really large numbers but something interesting which happens is that this throws a math overflowbut this below seems to work although I do not know if the value returned is correctAnybody aware why this happens <code> math.pow ( 1000 , 1000 ) 1000**100...
Why does one of these code segment work while the other throws an overflow
Python : I have list like belowI want add the elements based on index if 1st sublist element match with other list sublist elementtried with below : but output resulting like below : but correct output should be : <code> a= [ [ ' a',1,2,1,3 ] , [ ' b',1,3,4,3 ] , [ ' c',1,3,4,3 ] ] b= [ [ ' b',1,3,4,3 ] , [ ' c',1,3,4,...
Adding sublists elements based on indexing by condition in python
Python : I have a C # .NET classes that exist outside of a namespace that need to be accessed inside of IronPython . Typically I would do : However , I do not have a namespace . <code> import SomeNamespacefrom SomeNamespace import *
How do I import non namespaced types into IronPython ?
Python : In finance , futures contracts are usually represented by their expiry year and month . So for example , 201212 would be 2012 - December.Some contracts , for example Corn , are only traded some months [ 3,5,7,9,12 ] , whereas sometimes , you might only want to trade the [ 12 ] contract ( despite it trading oth...
Implementing a custom counting system in Python
Python : I have a dataframe like this , and I want to find the rows that contains list in that column . I tried value_counts ( ) but it tooks so long and throws error at the end . Here is the error : For bigger dataframes this tooks forever.Here is how the desired output look like : <code> import pandas as pddf = pd.Da...
How to check if a column contains list
Python : I 'm trying to take this dataframe ( with 1 row in this example ) : and to transform it to this : as you can see I need to change the value in respond to the columns and create rows , I understood I can do it using melt , but I 'm having hard time doing it.Please help me with that ... ..Thank you ! <code> id D...
melt columns and add 20 minutes to each row in date column
Python : today I bring you an apparently simple question , that it 's not so simple as it seems ( for me at least ) ! Imagine I have the following list of integers : And I want to print `` $ '' corresponding with the height i.e : prints this : However I want the former displayed ! I tried this : But after a while I und...
Print a list of heights with `` # '' symbol
Python : I want a commet in pygame to shoot across the screen . Here is my commet classThen i added 20 commets to the self.commets list.I am having two problems . The first problem being moving the commet . To move it i did thisFor x- coordinate i just added 2 to its value every frame . However , for the yvalue of the ...
Moving a comet in pygame
Python : I 'm new to python ( and coding in general ) , I 've gotten this far but I 'm having trouble . I 'm querying against a web service that returns a json file with information on every employee . I would like to pull just a couple of attributes for each employee , but I 'm having some trouble.I have this script s...
How do I pull a recurring key from a JSON ?
Python : For a self-project , I wanted to do something like : As you can see , I do n't really need more than one instance of Species ( id ) per id , but I 'd be creating one every time I 'm creating an Animal object with that id , and I 'd probably need multiple calls of , say , Animal ( somename , 3 ) .To solve that ...
Attempting to replicate Python 's string interning functionality for non-strings
Python : I 'm trying to fit a cubic spline to the data points below , I 'm a bit confused when I would use a Param like the example m.x = m.Param ( value=np.linspace ( -1 , 6 ) ) or when I would use a constant Const . <code> import numpy as npfrom gekko import GEKKOxm = np.array ( [ 0 , 1 , 2 , 3 , 4 , 5 ] ) ym = np.ar...
When do I use Param rather than Const in Gekko ?
Python : I 'm trying to get the files from specific folders in s3 Buckets : I have 4 buckets in s3 with the following names : The folder structure for all s3 buckets looks like this : I have to check if this folder prefix processed/files is present in the bucket , and if it is present , I 'll read the files present in ...
search in each of the s3 bucket and see if the given folder exists
Python : I feel like this should be done very easily , yet I ca n't figure out how . I have a pandas DataFrame with column date : I want to have a columns of durations , something like : My attempt yields bunch of 0 days and NaT instead : Any ideas ? <code> 0 2012-08-211 2013-02-172 2013-02-183 2013-03-034 2013-03-04Na...
Dates to Durations in Pandas
Python : I 'm looking for a short readable way to select some rows of an 2D numpy.ndarray , where the first number of each row is in some list . Example : So in this case i only need because the first numbers of these rows are 4 and 8 which are listed in index . Basically im looking for something like : which of course...
Select rows of numpy.ndarray where the first row number is inside some list
Python : All the Python docs I 've read appear to indicate that , side-effects aside , that if you import module A and then reference A.a , you are referencing the same variable as if you wrote `` from A import a '' .However , that does n't appear to be the case here and I 'm not sure what 's going on . I 'm using Pyth...
Why does from ... import appear to bind to value at import time in Python ?
Python : If need to say I found this powerful construct to extract matching strings from a list : ... but this is hard to read and overkill . I do n't want the list , I just want to know if such a list would have anything in it.Is there a simpler-reading way to get that answer ? <code> if < this list has a string in it...
Check if a list has one or more strings that match a regex
Python : I have two dataframesresults : acctypeDF : I wanted to combine both these dataframes into one so i did : But the output is : As you can see the output is repeating the index number 0.Why does this happen ? My objective is to drop the first index ( first column ) which has addresses , but I am getting this erro...
Why does my output dataframe have two columns with same indexes ?
Python : I 'm writing a class that has a number of methods operating on similar types of arguments : There 's a certain convention about these arguments ( e.g . data/params should be numpy.farrays , interval - a list of 2 floats ) , but I 'd like to allow user to have more freedom : e.g . functions should accept int as...
Pythonic way of converting parameters to the same standard within all methods of a class
Python : I 'm playing with a simple script to escape certain HTML characters , and am encountering a bug which seems to be caused by the order of elements in my list escape_pairs . I 'm not modifying the lists during a loop , so I ca n't think of any Python/programming principles I 'm overlooking here.returnsHowever wh...
Can the order of elements in a list cause a bug in a for loop ?
Python : Is there a numpy function that will convert something like : to an array of start/end pairs for the contiguous ranges , as : <code> [ 0 , 1 , 0 , 1 , 1 , 1 , 0 , 1 , 1 ] [ [ 1 , 2 ] , [ 3 , 6 ] , [ 7 , 9 ] ]
Convert boolean index to start/end pairs for runs
Python : The following code gives me error ValueError : Shapes ( None , 3 , 2 ) and ( None , 2 ) are incompatible . What I want to do is to construct a multi-task network . How should I resolve it ? I am using Tensorflow 2.3.0 . <code> import numpy as npimport tensorflow as tffrom tensorflow.keras.layers import GlobalA...
How to fix Keras ValueError : Shapes ( None , 3 , 2 ) and ( None , 2 ) are incompatible ?
Python : I 've a listand a list of dictionariesI want to sort this list_of_dct by the order given in order list , i.e . the output should be the following : I know how to sort by a given key , but not when an order is already given . How can I sort it ? PS : I already have an O ( n^2 ) solution . Looking for a better s...
Sort a list of dictionary provided an order
Python : I got a DataFrame with 3 levels of Index and I need to reindex the third level without changing the first and the second level.I have a DataFrame like this : And I would like a DataFrame like this : I want the third index to be the same everywhere <code> tuples = [ ( ' A ' , ' a ' , 1 ) , ( ' A ' , ' a ' , 3 )...
Reindex specific level of pandas MultiIndex
Python : Is there a way to identify leading and trailing NAs in a pandas.DataFrameCurrently I do the following but it seems not straightforward : Any ideas how this could be expressed more efficiently ? Answer : <code> import pandas as pddf = pd.DataFrame ( dict ( a= [ 0.1 , 0.2 , 0.2 ] , b= [ None , 0.1 , None ] , c= ...
Identify leading and trailing NAs in pandas DataFrame
Python : I have a DataFrame like thisI want to obtain a DataFrame Like this <code> gauge satellite1979-06-23 18:00:00 6.700000 2.4843781979-06-27 03:00:00 NaN 8.8914601979-06-27 06:00:00 1.833333 4.0534601979-06-27 09:00:00 NaN 2.8766491979-07-31 18:00:00 6.066667 1.438324 gauge satellite1979-06-23 18:00:00 6.700000 2....
How to change entire row if NaN present if a single column has NaN
Python : I want to raise exceptions that communicate some message and a value related to the error . I 'm wondering when it 's most appropriate to declare custom exceptions versus using the built-ins.I 've seen many examples like this and many more like it being recommended on other sites.I am much more inclined to wri...
When should I declare custom exceptions ?
Python : I am trying to a obtain a specific dictionary from within a list that contains both tuples and dictionaries . How would I go about returning the dictionary with key ' k ' from the list below ? <code> lst = [ ( 'apple ' , 1 ) , ( 'banana ' , 2 ) , { ' k ' : [ 1,2,3 ] } , { ' l ' : [ 4,5,6 ] } ]
Tuples and Dictionaries contained within a List
Python : Consider the following : I just thought it was a very strange restriction <code> st = `` Hi : % s , you are : % d '' x = [ 'user ' , 25 ] st % x # Does n't workst % ( `` user '' , 25 ) # Worksst % ( *x , ) # Works
Why can you format against a tuple but not a list ?
Python : I have an excel file where some of the rows are merged . Please find the snippet of the file below.And I want my file to look like the this : .As you can see First String and Second String are irrelevant to my data and I want to drop that row . Here is my trial.Where excel_file is the excel file I have importe...
How to remove the merged rows in excel using python ?
Python : For instance , I want to use numpy 's isnan function . I 've already loaded the pandas library : That works , but is there any disadvantage to that ? Or should I writeWhat is good practice ? <code> import pandas as pdpd.np.isnan ( 1 ) # = > False import pandas as pdimport numpy as npnp.isnan ( 1 ) # = > False
Is it unpythonic to use a package imported by another package , or should I import it directly ?
Python : For example , I have two arrays : How can I generate a pandas dataframe with every combination of x and y , like below ? <code> import numpy as npx = np.array ( [ 1,2,3 ] ) y = np.array ( [ 10 , 11 ] ) x y1 101 112 102 113 103 11
How to generate 2D mesh from two 1D arrays and convert it into a dataframe ?
Python : I have a 3-level MultiIndex dataframe and I would like to slice it such that all the values until a certain condition is met are kept . To make an example , I have the following dataframe : And I would like to select all the values until Col1 becomes smaller than Col2 . As soon as I have an instance for which ...
How to slice a pandas MultiIndex df keeping all values until a certain condition is met ?
Python : Expected output : Actual output : Is using unpacking assignment in combination with extended slice assignment not possible for some reason ? Why ? I do n't see anything obvious in PEP 3132 -- Extended Iterable Unpacking or in the Python datamodel suggesting this should n't be valid . <code> L = [ 0 , 1 , 2 ] L...
Iterable unpacking and slice assignment
Python : For some reason I ca n't seem to be able to update keys in the us-central1 region . My IAM have both the update and list roles and I use this code : It gives me the following error : google.api_core.exceptions.NotFound : 404 The request concerns location 'us-central1 ' but was sent to location 'global ' . Eith...
Ca n't update cryptokey in us-central1
Python : I have an issue with customizing the legend of my plot . I did lot 's of customizing but couldnt get my head around this one . I want the symbols ( not the labels ) to be equally spaced in the legend . As you can see in the example , the space between the circles in the legend , gets smaller as the circles get...
Matplotlib , vertical space between legend symbols
Python : My dataframe looks like this ; If col1 contains the value 1 in column 2 I want to forward fill with 1 n number of times . For example , if n = 4 then I would need the result to look like this.I think I could do this using a for loop with a counter that resets every time a condition occurs but is there a faster...
Forward fill column on condition
Python : In my application I have a lot of conditions under which it is non-sensical to run the app further.Currently I do something like this : There is a lot of boilerplate so I 'd like to avoid it . I 'm looking for something that would allow me to pass the string Some short description as a parameter and automate h...
How to handle exception and exit ?
Python : ( I 'm not sure if this question belongs here or CS forum . I kept it here because it has Python-specific code . Please migrate if needed ! ) I 'm studying algorithms these days , using Python as my tool of choice . Today , I wanted to plot the running times three variations of a simple problem : Compute the p...
These Python functions do n't have running times as expected
Python : Why does C += [ 5 ] modifies A but D = D + [ 5 ] does n't ? Is there any difference between = and += in python or any other language in that sense ? <code> > > > A = [ 1,2,3,4 ] > > > D = A > > > D [ 1 , 2 , 3 , 4 ] > > > D = D + [ 5 ] > > > A [ 1 , 2 , 3 , 4 ] > > > C = A > > > C += [ 5 ] > > > A [ 1 , 2 , 3 ...
Adding to lists in Python 2.7
Python : I regularly have a group of ( semantically ) related dynamic variables that are accessed by multiple methods and altered during runtime . I am currently fluctuating between three ways of highlighting their `` family '' and reduce the conceptual clutter in main : variable name prefix , use a class , or use a di...
Pythonic way to hold related variables ?
Python : Going off of the examples/basics/visuals/graphy.py , I tried to display a histogram but failed : and yet the text visual works just fine . I understand histogramVisual is a subclass of mesh , but I did n't see anything useful in the source code of mesh.py . I am using wx as my backend . <code> from vispy impor...
vispy visual.HistogramVisual
Python : I noticed a surprising behavior when trying to concatenate lists and tuples . Usually , they do n't mix : results in : TypeError : can only concatenate tuple ( not `` list '' ) to tupleand , vice versa gives : TypeError : can only concatenate list ( not `` tuple '' ) to listSo far , nothing was unexpected.Howe...
Inconsistent behavior concatenating lists and tuples in python
Python : Given a starter string , and a number of spaces needing to be added to a string , is there an easy way to do this ? If the number of spaces is uneven spread , add spaces left to right.This is what I 've tried : dividing space number with actual string spacestokenize stringIf first word just add the current wor...
Given amount of spaces needed to be added , format string by adding spaces between words
Python : I am attempting to generate a dataframe ( or series ) based on another dataframe , selecting a different column from the first frame dependent on the row using another series . In the below simplified example , I want the frame1 values from ' a ' for the first three rows , and ' b for the final two ( the picke...
Select columns in a DataFrame conditional on row
Python : How can I detect if user pressed the @ sign in pygame ? On some keyboard I need to press SHIFT + 2 , on others ALT + V , etc.This works : This does n't : This works only on one type of keyboard : So how can I detect if the user press @ without knowing the type of keyboard they use ? Thanks for the help . <code...
Detect if user pressed @ sign in pygame
Python : I 'm trying to write a function right now , and its purpose is to go through an object 's __dict__ and add an item to a dictionary if the item is not a function . Here is my code : If I 'm not mistaken , inspect.isfunction is supposed to recognize lambdas as functions as well , correct ? However , if I write t...
Adding items to a list if it 's not a function
Python : I need to create a function that takes the parameters ( character , stringOne , stringTwo ) . The function returns a new word which contain the same data as stringTwo + whatever characters in stringOne in the same position.Example : stringOne = `` apple '' stringTwo = `` 12345 '' character = `` p '' Should Ret...
Replacing characters from string one to string two
Python : I struggle with making lambdas work . The code here is example , but it shows my problem well.This give me 16 , but I expect to have different value for different lambda . Why is happening ! <code> lambdas = list ( ) for i in range ( 5 ) : lambdas.append ( lambda x : i*i*x ) print lambdas [ 0 ] ( 1 ) print lam...
Why my lambdas do not work ?
Python : I have a bunch of module imports that are the same across foo.py , bar.py , and baz.py . Is there a way I can do the imports in __init__.py ? What would I have to write in foo.py ? <code> pkg/ __init__.py foo.py bar.py baz.py
Importing across a python package
Python : In my code , df is defined like thisI have a [ 86 rows x 1 columns ] dataframe df which looks like this on print ( df ) I wish to write a code that would merge the Male and Female entries like thisThe final task I need to do is to .sum ( ) the male row and then the female row to get the total of each sex . I a...
How to sum rows with the same keys ?
Python : I have the following list of tuplesAnd I need to output the following textI have tried And it provides the following listBut have n't found an efficient way of getting the desired output , and it must work for a list of tuples of different sizes . <code> a = [ ( 5 , 2 ) , ( 2 , 4 ) ] ( 5,2 ) ( 2,4 ) [ `` , '' ...
Join a list of tuples with a formatting in an efficient manner
Python : I have DataFrame in which there is a column with event dates ( dates are not unique ) . I need to select all the data that is in this period . I try next : The type of column Transaction_date is datetime64 [ ns ] .When I run the code with the request for the period 01/01/2020 to 31/01/2020 - part of the data f...
Pandas : Select all data from Pandas DataFrame between two dates
Python : I have an array a = [ 1 , 2 , 3 , 4 , 5 , 6 ] and b = [ 1 , 3 , 5 ] and I 'd like to map a such that for every element in a that 's between an element in b it will get mapped to the index of b that is the upper range that a is contained in . Not the best explanation in words but here 's an exampleSo the final ...
Python - easy way to `` comparison '' map one array to another