lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | 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 accomplis... | X [ a , : ] [ : ,b ] | 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 tried thi... | indexlist = [ 0 , 7 , 8 , 12 , 19 , 25 , 26 , 27 , 29 , 30 , 31 , 33 ] outlist = [ 0 , 7 , 19 , 25 , 31 ] for index2 in range ( 0 , len ( indexlist ) - 1 ) : if indexlist [ index2 + 1 ] > indexlist [ index2 ] + 5 : outlist.append ( indexlist [ index2 ] ) outlist = [ 0 , 12 , 19 ] | 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 ? | 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 ? | ( [ 0-9 ] { 9 } | [ 0-9 ] { 12 } ) | 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 when I dep... | app.get ( '/perform/ : word ' , readOut ) function readOut ( req , res ) { var spawn = require ( `` child_process '' ) .spawn ; var process = spawn ( 'python ' , [ `` ./readout.py '' , req.params.word ] ) ; res.send ( `` Action completed ! '' ) } import osimport sysos.system ( 'say { } '.format ( sys.argv [ 1 ] ) ) std... | 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 ] ? | alist1_temp= [ 1 , 4,2 ] alist2_temp= [ 3 , 7,4 ] t= [ [ x , y ] for x , y in zip ( alist1_temp , alist2_temp ) ] | 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 | class Suppiler ( models.Model ) : _inherit = `` res.partner '' author= fields.Boolean ( string='Author ' ) < data > < record id= '' add_supplier_view_inherit '' model= '' ir.ui.view '' > < field name= '' name '' > res.partner.form < /field > < field name= '' model '' > res.partner < /field > < ! -- < field name= '' pri... | 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 correspond... | import pandas as pd distances = { 'names ' : [ ' A ' , ' B ' , ' C ' ] , 'distances ' : [ 100 , 200 , 300 ] } dates = { 'flights ' : [ ' C ' , ' B ' , ' A ' ] , 'dates ' : [ ' 1/1/16 ' , ' 1/2/16 ' , ' 1/3/16 ' ] } distancesDF = pd.DataFrame ( distances ) datesDF = pd.DataFrame ( dates ) distances names0 100 A1 200 B2 ... | 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 . ( Above , they ... | class base : def __init__ ( self , v ) : self.value = v def doThings ( self ) : print `` Doing things . '' def doMoreThings ( self ) : print `` Doing more things . '' def combine ( self , b ) : self.value += b.valueclass foo ( base ) : def showValue ( self ) : print `` foo value is % d . '' % self.valueclass bar ( base... | 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 metaprogramming fea... | …self.debug = 0self.token = `` self.filestack = deque ( ) self.source = Noneif self.debug : print 'shlex : reading from % s , line % d ' \ % ( self.instream , self.lineno ) | 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 them . You... | import java.io . * ; public class Main { int pieces , people ; int combinations = 0 ; public void calculate ( int person , int piecesLeft , int prev ) { if ( person == people ) { if ( piecesLeft == 0 ) combinations++ ; } else { for ( int x = prev ; ( x * ( people - person ) ) < = piecesLeft ; x++ ) { calculate ( person... | 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 , and ge... | d1 = { k : v for k , v in d1.items ( ) if cond ( v ) } for k , v in d1.items ( ) : if not cond ( v ) : d1.pop ( k ) | 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 ? | def change ( elements ) : elements [ 0 ] = 888 elements = [ -3 , -1 , -2 , -3 , -4 ] print ( elements [ 0 ] ) numbers = [ 1 , 4 , 5 ] print ( numbers [ 0 ] ) change ( numbers ) print ( numbers [ 0 ] ) print ( numbers ) 1-3 , 888 [ 888,4,5 ] 1 , -3 , -3 , [ -3 , -1 , -2 , -3 , -4 ] | 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 symmetry to cut... | A = np.zeros ( ( N , N , N , N ) ) for a in range ( N ) : for b in range ( N ) : for c in range ( N ) : for d in range ( N ) : A [ a , b , c , d ] = f ( a , b , c , d ) A = np.zeros ( ( N , N , N , N ) ) ab = 0for a in range ( N ) : for b in range ( N ) : ab += 1 cd = 0 for c in range ( N ) : for d in range ( N ) : cd ... | 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 ? | 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 , 9 fulfi... | df = pd.DataFrame ( { 'ID ' : [ 'A001 ' , 'A001 ' , 'A001 ' , 'A002 ' , 'A002 ' , 'A003 ' , 'A003 ' , 'A004 ' , 'A004 ' , 'A004 ' , 'A005 ' , 'A005 ' ] , 'Val1 ' : [ 2 , 2 , 2 , 5 , 6 , 8 , 8 , 3 , 3 , 3 , 7 , 7 ] , 'Val2 ' : [ 100 , -100 , 50 , -40 , 40 , 60 , -50 , 10 , -10 , 10 , 15 , 15 ] } ) ID Val1 Val2 0 A001 2 ... | 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 lines , less... | import sysimport osimport socketimport shutilimport threadingimport urllibimport timeimport zipfile import sys , os , socket , shutil , threading , urllib , time , zipfile import sys , os , shutilimport threadingimport zipfileimport socket , urllibimport time | 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 I 'm dea... | id | item_numA123 | 1A123 | 2B456 | 1 id | descriptionA123 | Mary had a ... A123 | ... little lamb.B456 | ... Its fleece ... id | item_num | descriptionA123 | 1 | Mary had a ... A123 | 2 | Mary had a ... A123 | 1 | ... little lamb.A123 | 2 | ... little lamb.B456 | 1 | Its fleece ... id | item_num | descriptionA123 | 1 ... | 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 queries tog... | data = { 'Name ' : [ 'Penny ' , 'Ben ' , 'Benny ' , 'Mark ' , 'Ben1 ' , 'Ben2 ' , 'Ben3 ' ] , 'Eng ' : [ 5,1,4,3,1,2,3 ] , 'Math ' : [ 1,5,3,2,2,2,3 ] , 'Physics ' : [ 2,5,3,1,1,2,3 ] , 'Sports ' : [ 4,5,2,3,1,2,3 ] , 'Total ' : [ 12,16,12,9,5,8,12 ] , 'Group ' : [ ' A ' , ' A ' , ' A ' , ' A ' , ' A ' , ' B ' , ' B ' ... | 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 : Client uploa... | def download ( self , cmd ) : try : self.c.send ( str.encode ( cmd ) ) command , filename=cmd.split ( ' ' ) nFile = open ( filename , 'wb ' ) i = self.c.recv ( 1024 ) while not ( 'complete ' in str ( i ) ) : nFile.write ( i ) i = self.c.recv ( 1024 ) nFile.close ( ) self.reset = True print ( '\nGot that file ' ) except... | 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 techniques such ... | DynoOne = createClass ( 'DynoOne ' , props= [ ' A ' , ' B ' ] ) d = DynoOne ( database='XYZ ' ) d.A = d.B + 1 DynoTwo = createClass ( 'DynoTwo ' , props= [ ' A ' , ' C ' , ' E ' ] ) q = DynoTwo ( database='QRS ' ) q.A = q.C + 2*q.E class DynamicClass ( someBase ) : def dynamic_getter ( self ) : # acquire `` stuff '' re... | 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 trying , a... | import csvoutFile = `` output.csv '' f = open ( outFile , `` w '' ) row = [ 'hello , world ' , '43333 ' , '44141 ' ] with open ( outFile , ' w ' ) as writeFile : writer = csv.writer ( writeFile ) writer.writerow ( row ) writeFile.close ( ) | 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 . Instrument List : ... | counter = [ 13 ] instruments = [ ' 3\t -- - ' , ' 2\t / \\ ' , ' 1\t / \\ ' , ' 0\t -- - \\ -- - ' , '-1\t \\ / ' , '-2\t \\ / ' , '-3\t -- - ' ] score = [ '|*************| ' ] 3 -- -2 / \1 / \0 -- - \ -- -- 1 \ /-2 \ /-3 -- - |*************| 3 ***2 * *1 * *0 *** * -1 * -2 * -3 3 ***2 * *1 * *0 *** * **-1 -2 -3 for ele... | 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 scenario ) | class A ( object ) : passclass B ( object ) : passclass C ( object ) : passclasses = [ A , B , C ] class D ( *classes ) : pass | 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 ? | segment = len ( list ) //ksub_lists = [ list [ i : i+segment ] for i in range ( 0 , len ( list ) , segment ) ] k = 2list = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ] list = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] ] list = [ [ [ 1 , 2 ] , [ 3 , 4 ] ] , [ [ 5 , 6 ] , [ 7 , 8 ] ] ] list = [ [ [ [ 1 ] , [ 2 ] ] , [ [ 3 ] , [ 4 ] ] ... | 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 it ? | 0.03 // 0.01 > > > 2.0 3.0 // 1.0 > > > 3.0 | 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 see which f... | $ locate signals.py | grep python/usr/lib/pymodules/python2.7/zim/signals.py/usr/lib/pymodules/python2.7/zim/signals.pyc/usr/lib/python2.7/dist-packages/bzrlib/smart/signals.py/usr/lib/python2.7/dist-packages/bzrlib/smart/signals.pyc/usr/lib/python2.7/unittest/signals.py/usr/lib/python2.7/unittest/signals.pyc/usr/lib/p... | 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 get the re... | In [ 138 ] : ; list ( 'ab ' ) Out [ 138 ] : [ ' ( ' , `` ' '' , ' a ' , ' b ' , `` ' '' , ' ) ' ] | 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 and functio... | l = [ 1,2,3 ] x = [ ( a , b ) for a in l for b in l ] y = [ ( a + b ) for a in l for b in l ] x = [ ( 1 , 1 ) , ( 1 , 2 ) , ( 1 , 3 ) , ( 2 , 1 ) , ( 2 , 2 ) , ( 2 , 3 ) , ( 3 , 1 ) , ( 3 , 2 ) , ( 3 , 3 ) ] y = [ 2 , 3 , 4 , 3 , 4 , 5 , 4 , 5 , 6 ] mysetup = `` '' '' from itertools import productl = [ 10 , 15 , 3 , 7 ... | 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.8582800000000001539... | # # Decimal has all of the methods specified by the Real abc , but it should # # not be registered as a Real because decimals do not interoperate with # # binary floats ( i.e . Decimal ( ' 3.14 ' ) + 2.71828 is undefined ) . But , # # abstract reals are expected to interoperate ( i.e . R1 + R2 should be # # expected to... | 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 . Using { 'f... | things = { 'foo ' , 'bar ' , 'baz ' } > > > 'foo ' in things or 'bar ' in thingsTrue | 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 do somet... | class test ( object ) : def __init__ ( self , myNum ) : self.myNum=myNum def giveMyNum ( self ) : print `` giving '' return self.myNumq= [ test ( x ) for x in range ( 3 ) ] print [ x.giveMyNum ( ) for x in q if x.giveMyNum ( ) > 1 ] ret= [ ] for x in q : k=x.giveMyNum ( ) if k > 1 : ret.append ( k ) | 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 Nones and ... | def tokenize ( s ) : import re pattern = re.compile ( `` ( \-|\+\=|\=\=|\=|\+ ) |\s+ '' ) return pattern.split ( s ) print ( tokenize ( `` hello-+==== =+ there '' ) ) [ 'hello ' , '- ' , '+= ' , '== ' , '= ' , '= ' , '+ ' , 'there ' ] [ 'hello ' , '- ' , `` , '+= ' , `` , '== ' , `` , '= ' , `` , None , `` , '= ' , `` ... | 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 | df = pd.DataFrame ( { 'demographic ' : [ ' A ' , ' B ' , ' B ' , ' A ' , ' C ' , ' C ' ] , 'id_match ' : [ '101 ' , '101 ' , '201 ' , '201 ' , '26 ' , '26 ' ] , 'time ' : [ '10 ' , '10 ' , '16 ' , '16 ' , ' 1 ' , ' 1 ' ] } ) A B CA 0 52 0B 52 0 0C 0 0 2 | 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 complete 1... | def getElements ( i , arr , size=10 ) : return cyclic array return a = [ 0,1,2,3,4,5,6,7,8,9,10,11 ] b = getElements ( 9 , a ) > > b > > [ 9,10,11,0,1,2,3,4,5,6 ] b = getElements ( 1 , a ) > > b > > [ 1,2,3,4,5,6,7,8,9,10 ] def getElements ( i , arr , size=10 ) : total = len ( arr ) start = i % total end = start+size r... | 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 . | def remove_vowels ( string ) : vowels = [ ' a ' , ' e ' , ' i ' , ' o ' , ' u ' ] newstring = `` '' for letter in string : if letter in vowels : newstring = string.replace ( letter , ” ” ) else : pass return newstring | 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 used as k... | from gc import get_referrers as refsx = ' x 'd = { x : x } print ( d in refs ( x ) ) | 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 becomes a va... | `` abracadabra '' → { ' r ' : 2 , 'd ' : 1 , ' c ' : 1 , ' b ' : 2 , ' a ' : 5 } xs = `` hshhsf '' xsUnique = `` '' .join ( set ( xs ) ) occurrences = [ ] freq = [ ] counter = 0for i in range ( len ( xsUnique ) ) : for x in range ( len ( xs ) ) : if xsUnique [ i ] == xs [ x ] : occurrences.append ( xs [ x ] ) counter +... | 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 . lets go... | pygame.display.set_mode ( ( 740 , 440 ) , pygame.RESIZABLE ) elif event.type == pygame.VIDEORESIZE : game.screen = pygame.display.set_mode ( ( event.w , event.h ) , pygame.RESIZABLE ) # Code to re-size other important surfaces import sysimport pygamepygame.init ( ) size = 320 , 240black = 0 , 0 , 0red = 255 , 0 , 0scre... | 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 inputThe array ... | [ [ 1,1,2,2 , ] , [ 1,1,2,2 , ] , [ 3,3,4,4 , ] , [ 3,3,4,4 ] ] def operation ( mat , step=2 ) : result = np.array ( mat , copy=True ) result [ : :2 , ::2 ] = mat return result [ [ 98.+0.j 0.+0.j 40.+0.j 0.+0.j ] [ 0.+0.j 0.+0.j 0.+0.j 0.+0.j ] [ 29.+0.j 0.+0.j 54.+0.j 0.+0.j ] [ 0.+0.j 0.+0.j 0.+0.j 0.+0.j ] ] [ [ 98 ... | 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 can I co... | .children [ 0 ] .children [ 9 ] .children [ 0 ] .children [ 0 ] .handle = PCI:0000:01:00.0.children [ 0 ] .children [ 9 ] .children [ 0 ] .children [ 0 ] .description = Non-Volatile memory controller.children [ 0 ] .children [ 9 ] .children [ 0 ] .children [ 0 ] .product = Samsung Electronics Co Ltd.children [ 0 ] .chi... | 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 even mor... | > > > def is_not_bound ( inst , name ) : ... print ( `` Hello % s '' % name ) ... > > > > > > class NoMethods : ... pass ... > > > > > > setattr ( NoMethods , 'bound ' , is_not_bound ) > > > > > > NoMethods ( ) .bound ( `` oz '' ) # prints : Hello ozHello oz > > > class Foo : ... def foo ( self , name ) : ... print ( `... | 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 : | import numpy as npimport plotly.graph_objects as gofig = go.Figure ( ) fig.add_trace ( go.Contour ( z=np.random.rand ( 10,10 ) , x=np.linspace ( 0,10,10 ) , y=np.linspace ( 0,10,10 ) , contours=dict ( start=0 , end=1 , size=0.25 , ) , colorbar=dict ( tick0=0 , dtick=1 ) ) ) fig.show ( ) | 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 so it was... | ExecStart=/usr/bin/python3 /home/pi/Desktop/scanner.py import pygame.mixer # sets up soundpygame.mixer.init ( ) goodscan = pygame.mixer.Sound ( '/home/pi/Desktop/goodscan.wav ' ) duplicatescan = pygame.mixer.Sound ( '/home/pi/Desktop/duplicateScan.wav ' ) badscan = pygame.mixer.Sound ( '/home/pi/Desktop/badScan.wav ' )... | 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 to be expe... | > > > 2**7 is 2**7True > > > 2**10 is 2**10False > > > 10000000000000000000000000000000000000000 is 10000000000000000000000000000000000000000True | 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 ? | import timeimport loggingimport asyncioimport aiohttpimport jsonfrom aiohttp import ClientSession , ClientResponseErrorfrom aiocfscrape import CloudflareScraperasync def nested ( url ) : async with CloudflareScraper ( ) as session : async with session.get ( url ) as resp : return await resp.text ( ) async def main ( ) ... | 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 get the ... | import serialimport numpyimport matplotlib.pyplot as pltfrom drawnow import *data = serial.Serial ( 'com3',115200 ) while True : while ( data.inWaiting ( ) == 0 ) : passardstr = data.readline ( ) print ( ardstr ) | 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 | math.pow ( 1000 , 1000 ) 1000**1000 | 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 : | 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,3 ] ] from operator import add res_list1= [ ] for a1 in a : for b1 in b : if a1 [ 0 ] ==b1 [ 0 ] : res_list = [ map ( add , a1 [ 1 : ] , b1 [ 1 : ] ) ] res = [ [ a1 [ 0 ] , i , j , k , l ] for i , j , k , l in res_list ] ... | 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 . | 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 other months... | def contract_generator ( self , recent=True , year=None , month=None , traded_only=False ) : if year is None : year = datetime.datetime.now ( ) .year - 1 if recent == True else self.first_contract if traded_only is True : months = self.trade_only else : months = self.months_traded months = deque ( months ) if month is ... | 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 : | import pandas as pddf = pd.DataFrame ( { `` col1 '' : [ `` a '' , `` b '' , `` c '' , [ `` a '' , `` b '' ] ] } ) TypeError Traceback ( most recent call last ) pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.map_locations ( ) TypeError : unhashable type : 'list'Exception ignored in :... | 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 ! | id Date value_now value+20min value+60min value+80min0 2015-01-11 00:00:01 12 15 18 22 id Date Value0 2015-01-11 00:00:01 12 0 2015-01-11 00:20:01 15 0 2015-01-11 00:40:01 18 0 2015-01-11 01:00:01 22 | 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 understood t... | num = [ 3,1,1,2 ] & & & & & & & for i in num : print ( `` # '' *i ) & & & & & & & for i in range ( 1 , max ( num ) +1 ) : # loops through the rows for j in num : if j == i : print ( `` # '' ) else : print ( `` '' ) | 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 commet , ... | class Commet : def __init__ ( self ) : self.x = -10 self.y = 10 self.radius = 20 self.commet = pygame.image.load ( r '' C : \Users\me\OneDrive\Documents\A level python codes\final game\commet.png '' ) self.commet = pygame.transform.scale ( self.commet , ( self.radius , self.radius ) ) self.drop = 0.0000009 self.speed =... | 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 so far : T... | import jsonimport urllib2req = urllib2.Request ( 'http : //server.company.com/api ' ) response = urllib2.urlopen ( req ) the_page = response.read ( ) j = json.loads ( the_page ) print j [ 1 ] [ 'name ' ] { `` name '' : bill jones , `` address '' : `` 123 something st '' , `` city '' : `` somewhere '' , `` state '' : ``... | 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 , what I ... | class Species ( object ) : # immutable . def __init__ ( self , id ) : # ... ( using id to obtain height and other data from file ) def height ( self ) : # ... class Animal ( object ) : # mutable . def __init__ ( self , nickname , species_id ) : self.nickname = nickname self.species = Species ( id ) def height ( self ) ... | 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 . | import numpy as npfrom gekko import GEKKOxm = np.array ( [ 0 , 1 , 2 , 3 , 4 , 5 ] ) ym = np.array ( [ 0.1 , 0.2 , 0.3 , 0.5 , 1.0 , 0.9 ] ) m = GEKKO ( ) m.x = m.Param ( value=np.linspace ( -1 , 6 ) ) m.y = m.Var ( ) m.options.IMODE = 2m.cspline ( m.x , m.y , xm , ym ) m.solve ( disp=False ) p = GEKKO ( ) p.x = p.Var ... | 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 those dir... | 1 - 'PDF ' 2 - 'TXT ' 3 - 'PNG ' 4 - 'JPG ' 1- PDF/analysis/pdf-to-img/processed/files2- TXT/report/processed/files3- PNG/analysis/reports/png-to-txt/processed/files4- JPG/jpg-to-txt/empty buckets = [ 'PDF ' , 'TXT ' , 'PNG ' , 'JPG ' ] client = boto3.client ( 's3 ' ) for i in bucket : result = client.list_objects ( Bu... | 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 ? | 0 2012-08-211 2013-02-172 2013-02-183 2013-03-034 2013-03-04Name : date , dtype : datetime64 [ ns ] 0 01 80 days2 1 day3 15 days4 1 dayName : date , dtype : datetime64 [ ns ] > > > df.date [ 1 : ] - df.date [ : -1 ] 0 NaT1 0 days2 0 days ... | 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 is not w... | > > > index [ 4 , 8 ] > > > data array ( [ [ 0 , 1 , 2 , 3 ] , [ 4 , 5 , 6 , 7 ] , [ 8 , 9 , 10 , 11 ] , [ 12 , 13 , 14 , 15 ] ] ) array ( [ [ 4 , 5 , 6 , 7 ] , [ 8 , 9 , 10 , 11 ] ] ) data [ data [ : ,0 ] == i if i in index ] | 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 Python 2.6.1.... | bravo = Nonedef set_bravo ( ) : global bravo bravo = 1 import sys , ossys.path.append ( os.path.abspath ( ' . ' ) ) import alphafrom alpha import bravoalpha.set_bravo ( ) print `` Value of bravo is : % s '' % bravoprint `` Value of alpha.bravo is : % s '' % alpha.bravo Value of bravo is : NoneValue of alpha.bravo is : ... | 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 ? | if < this list has a string in it that matches this rexeg > : do_stuff ( ) [ m.group ( 1 ) for l in my_list for m in [ my_regex.search ( l ) ] if m ] | 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 error : I als... | 0 2211 E Winston Rd Ste B , 92806 , CA 33.814547 -117.886028 4 1 P.O . Box 5601 , 29304 , SC 34.945855 -81.930035 6 2 4113 Darius Dr , 17025 , PA 40.287768 -76.967292 8 0 rooftop1 place2 rooftop import pandas as pdresultsfinal = pd.concat ( [ results , acctypeDF ] , axis=1 ) resultsfinalOut [ 155 ] : 0 1 2 3 00 2211 E ... | 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 data or ... | class TheClass ( ) : def func1 ( self , data , params , interval ) : ... . def func2 ( self , data , params ) : ... . def func3 ( self , data , interval ) : ... . def func4 ( self , params ) : ... . ... def convertparameters ( *types ) : def wrapper ( func ) : def new_func ( self , *args , **kwargs ) : # Check if we go... | 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 when I swit... | escape_pairs = [ ( `` > '' , `` & gt ; '' ) , ( `` < `` , '' & lt ; '' ) , ( ' '' ' , '' & quot ; '' ) , ( `` & '' , '' & amp ; '' ) ] def escape_html ( s ) : for ( i , o ) in escape_pairs : s = s.replace ( i , o ) return sprint escape_html ( `` > '' ) print escape_html ( `` < `` ) print escape_html ( ' '' ' ) print es... | 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 : | [ 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 . | import numpy as npimport tensorflow as tffrom tensorflow.keras.layers import GlobalAveragePooling2D , Dense , Dropoutfrom tensorflow.keras import Modelbase_model = tf.keras.applications.EfficientNetB7 ( input_shape= ( 32,32 , 3 ) , weights='imagenet ' , include_top=False ) # or weights='noisy-student'for layer in base_... | 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 solution . | order = [ 8 , 7 , 5 , 9 , 10 , 11 ] list_of_dct = [ { 'value':11 } , { 'value':8 } , { 'value':5 } , { 'value':7 } , { 'value':10 } , { 'value':9 } ] list_of_dct = [ { 'value':8 } , { 'value':7 } , { 'value':5 } , { 'value':9 } , { 'value':10 } , { 'value':11 } ] | 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 | tuples = [ ( ' A ' , ' a ' , 1 ) , ( ' A ' , ' a ' , 3 ) , ( ' A ' , ' b ' , 3 ) , ( ' B ' , ' c ' , 1 ) , ( ' B ' , ' c ' , 2 ) , ( ' B ' , ' c ' , 3 ) , ( ' C ' , 'd ' , 2 ) ] idx = pd.MultiIndex.from_tuples ( tuples , names= [ 'first ' , 'second ' , 'third ' ] ) df = pd.DataFrame ( np.random.randn ( 7 , 2 ) , index=... | 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 : | import pandas as pddf = pd.DataFrame ( dict ( a= [ 0.1 , 0.2 , 0.2 ] , b= [ None , 0.1 , None ] , c= [ 0.1 , None , 0.1 ] ) lead_na = ( df.isnull ( ) == False ) .cumsum ( ) == 0trail_na = ( df.iloc [ : :-1 ] .isnull ( ) == False ) .cumsum ( ) .iloc [ : :-1 ] == 0trail_lead_nas = top_na | trail_na % timeit df.ffill ( ) ... | Identify leading and trailing NAs in pandas DataFrame |
Python | I have a DataFrame like thisI want to obtain a DataFrame Like this | 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.4843781979-06-27 03:00:00 NaN NaN1979-06-27 06:00:00 1.833333 4.0534601979-06-27 09... | 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 write code s... | class NameTooShortError ( ValueError ) : passdef validate ( name ) : if len ( name ) < 10 : raise NameTooShortError ( name ) def validate ( name ) : if len ( name ) < 10 : raise ValueError ( f '' Name too short : { name } '' ) | 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 ? | 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 | 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 imported to the ... | rule1 = lambda x : x not in [ `` ] u = excel_file.loc [ excel_file [ 'Date1 ' ] .apply ( rule1 ) & excel_file [ 'Date2 ' ] .apply ( rule1 ) & excel_file [ 'ID ' ] .apply ( rule1 ) & excel_file [ 'Supervisor ' ] .apply ( rule1 ) ] .indexexcel_file.iloc [ u , : ] Date1 Date2 ID Supervisor0 2019-12-05 2019-12-05 5865 Jack... | 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 ? | 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 ? | 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 Col1 < Co... | Col1 Col2Date Range Label'2018-08-01 ' 1 A 900 815 B 850 820 C 800 820 D 950 840 2 A 900 820 B 750 850 C 850 820 D 850 800 Col1 Col2Date Range Label'2018-08-01 ' 1 A 900 815 B 850 820 2 A 900 820 df_new=df [ df [ 'Col1 ' ] > df [ 'Col2 ' ] ] idx = pd.IndexSliceidx_lev1=df.index.get_level_values ( 1 ) .unique ( ) for j ... | 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 . | L = [ 0 , 1 , 2 ] L [ : :2 ] , *rest = `` abcdef '' print ( L , rest ) [ ' a ' , 1 , ' b ' ] [ ' c ' , 'd ' , ' e ' , ' f ' ] ValueError : attempt to assign sequence of size 1 to extended slice of size 2 | 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 ' . Either Cloud ... | import google.cloud.kms as kmsself.client = kms.KeyManagementServiceClient ( ) name = 'client-1'key_path = self.client.crypto_key_path ( config.PROJECT , config.KMS_LOCATION , config.KMS_RING , name ) update_mask = { 'paths ' : [ 'rotation_period ' , 'next_rotation_time ' ] } self.client.update_crypto_key ( { 'name ' :... | 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 bigger.a... | import pandas as pdimport matplotlib.pyplot as pltfrom vega_datasets import data as vega_datagap = pd.read_json ( vega_data.gapminder.url ) df = gap.loc [ gap [ 'year ' ] == 2000 ] fig , ax = plt.subplots ( 1 , 1 , figsize= [ 14,12 ] ) ax=ax.scatter ( df [ 'life_expect ' ] , df [ 'fertility ' ] , s = df [ 'pop ' ] /100... | 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 way to p... | df = pd.DataFrame ( { 'Col1 ' : [ 0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0 ] , 'Col2 ' : [ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ] } ) df = pd.DataFrame ( { 'Col1 ' : [ 0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0 ] , 'Col2 ' : [ 0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,0,0,1,1,1,1 ] } ) | 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 handling t... | try : some_fun ( ) except Exception as e : print ( f'Some short description : { str ( e ) } ' ) sys.exit ( 1 ) | 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 prefix ave... | import timeitseq = [ 20 , 45 , 45 , 40 , 12 , 48 , 67 , 90 , 0 , 56 , 12 , 45 , 67 , 45 , 34 , 32 , 20 ] # Quadratic running timedef quad ( S ) : n = len ( S ) A = [ 0 ] * n for j in range ( n ) : total = 0 for i in range ( j+1 ) : total += S [ i ] A [ j ] = total / ( j+1 ) return A # Use prev resultdef prev ( S ) : n ... | 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 ? | > > > 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 , 4 , 5 ] | 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 dictionary.... | # Prefixkey_bindings_chars = { 'right ' : '- > ' , 'left ' : ' < - ' } key_bindings_codes = [ 'smooth ' , 'spiky ' ] key_bindings_hints = [ 'Smooth protrutions ' , 'Spiky protrutions ' ] print ( key_bindings_chars [ 'right ' ] ) # As a classclass key_bindings ( object ) : chars = { 'right ' : '- > ' , 'left ' : ' < - '... | 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 . | from vispy import app , visualsimport wximport numpy as npclass snrHistogram ( app.Canvas ) : def __init__ ( self , *args , **kwargs ) : app.Canvas.__init__ ( self , title='histogram fail ' , keys= '' interactive '' , size= ( 600 , 600 ) ) self.snr_hist = visuals.HistogramVisual ( np.arange ( 256 ) , bins=4 , color= ' ... | 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.However , if ... | ( 0 , 1 ) + [ 2 , 3 ] [ 0 , 1 ] + ( 2 , 3 ) l = [ 0 , 1 ] l += ( 2 , 3 ) l t = ( 0 , 1 ) t += [ 2 , 3 ] t | 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 word w/o spa... | div = spaces // ( word_count - 1 ) temp = st.split ( ) for i in range ( len ( temp ) ) : if i == 0 : st = temp [ 0 ] else : st = st + `` `` *div + `` `` +temp [ i ] space_count = space_count - div if space_count < = word_count -1 : st = st.replace ( `` `` , `` `` , space_count ) Algernon . Did you hear what I was playi... | 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 picked_values ... | frame1=pd.DataFrame ( np.random.randn ( 10 ) .reshape ( 5,2 ) , index=range ( 5 ) , columns= [ ' a ' , ' b ' ] ) picked_values=pd.Series ( [ ' a ' , ' a ' , ' a ' , ' b ' , ' b ' ] ) a b0 0.283519 1.4622091 -0.352342 1.2540982 0.731701 0.2360173 0.022217 -1.4693424 0.386000 -0.706614 0 0.2835191 -0.3523422 0.7317013 -1... | 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 . | if event.type == pygame.KEYDOWN : if event.key == pygame.K_RETURN : print ( `` ENTER key pressed '' ) if event.type == pygame.KEYDOWN : if event.key == pygame.K_AT : print ( `` @ sign pressed '' ) if event.type == pygame.KEYDOWN : if event.key == pygame.K_2 : if pygame.key.get_mods ( ) & pygame.KMOD_SHIFT : print ( `` ... | 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 then my fu... | def dict_into_list ( self ) : result = { } for each_key , each_item in self.__dict__.items ( ) : if inspect.isfunction ( each_key ) : continue else : result [ each_key ] = each_item return result c = some_object ( 3 ) c.whatever = lambda x : x*3 class WhateverObject : def __init__ ( self , value ) : self._value = value... | 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 Return `` 1p... | def replace ( char , word1 , word2 ) : newWord = `` '' for s in range ( len ( word1 ) ) : if word1 [ s ] == char : return | 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 ! | lambdas = list ( ) for i in range ( 5 ) : lambdas.append ( lambda x : i*i*x ) print lambdas [ 0 ] ( 1 ) print lambdas [ 2 ] ( 1 ) | 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 ? | 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 am new to ... | df = pd.read_excel ( io=file_name , sheet_name=sheet , sep='\s* , \s* ' ) 0Male 511Female 461Male 273Female 217Male 394Female 337Female 337Male 337 ... 0 1 2 3 ... Male 511 273 394 337 ... Female 461 217 337 337 ... print ( df.ix [ 'Female ' ] .sum ( ) ) print ( df.ix [ 'Male ' ] .sum ( ) ) | 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 . | a = [ ( 5 , 2 ) , ( 2 , 4 ) ] ( 5,2 ) ( 2,4 ) [ `` , '' .join ( str ( i ) for i in j ) for j in a ] [ ' 5,3 ' , ' 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 for the sp... | start_day = datetime.date ( datetime.strptime ( start_day , ' % d. % m. % Y ' ) ) # change user data to date formatend_day = datetime.date ( datetime.strptime ( end_day , ' % d. % m. % Y ' ) ) df = df [ df [ 'Transaction_date ' ] .between ( start_day , end_day ) ] | 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 product I... | a = 1 - > 0 because a < = first element of ba = 2 - > 1 because b [ 0 ] < 2 < = b [ 1 ] and b [ 1 ] = 3a = 3 - > 1 a = 4 - > 2 because b [ 1 ] < 4 < = b [ 2 ] | Python - easy way to `` comparison '' map one array to another |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.