lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | How can I compare each object with each and if ratio ( ) > 0.7 set possible_duplicate=True for both objects ? My try : | from difflib import SequenceMatcherclass Item ( models.Model ) : name = models.CharField ( max_length=255 ) desc = models.TextField ( ) possible_duplicate = models.BooleanField ( default=False ) items = Item.objects.all ( ) for item in items : obj = Item.objects.get ( pk=item.pk ) similarity = SequenceMatcher ( None , ... | How can I compare each object with each ? |
Python | It works in normal python interactive mode : However , the second \n is gone in iPythonWhat 's wrong ? | > > > `` '' '' 1 ... ... 2 '' '' '' ' 1\n\n2 ' In [ 4 ] : `` '' '' 1 ... : ... : 2 '' '' '' Out [ 4 ] : ' 1\n2 ' | iPython did n't catch the empty line as a ` \n ` |
Python | What is the pythonic way to PEP-8-ify such as with statement : I could do this but since the tempfile i/o is not with the with statement , does it automatically close after the with ? Is that pythonic ? : Or I could use slashes : But is that PEP8 comply-able ? Is that pythonic ? | with tempfile.NamedTemporaryFile ( prefix='malt_input.conll . ' , dir=self.working_dir , mode= ' w ' , delete=False ) as input_file , tempfile.NamedTemporaryFile ( prefix='malt_output.conll . ' , dir=self.working_dir , mode= ' w ' , delete=False ) as output_file : pass intemp = tempfile.NamedTemporaryFile ( prefix='mal... | Keeping 80 chars margin for long with statement ? |
Python | I have an abstract base class Bicycle : and a subclass MountainBike : The following code will cause a recursion error , but if I remove self from the super ( ) .__init__ ( self ) , the call to __str__ ( self ) : works.Question : I only discovered this error when I implemented the __str__ ( self ) : In Python 3.x when c... | from abc import ABC , abstractmethodclass Bicycle ( ABC ) : def __init__ ( self , cadence = 10 , gear = 10 , speed = 10 ) : self._cadence = cadence self._gear = gear self._speed = speed @ abstractmethod def ride ( self ) : pass def __str__ ( self ) : return `` Cadence : { 0 } Gear : { 1 } Speed : { 2 } '' .format ( sel... | Declaring Subclass without passing self |
Python | I have a list of dictionaries like this : How can I transform the above list into ? ( * ) : I tried to use .items ( ) and l [ 1 ] : However , I was not able to extract the second element position of the list of dictionaries into a list of tuples , as ( * ) | l = [ { 'pet ' : 'cat ' , 'price ' : '39.99 ' , 'available ' : 'True ' } , { 'pet ' : 'cat ' , 'price ' : '67.99 ' , 'available ' : 'True ' } , { 'pet ' : 'dog ' , 'price ' : '67.00 ' , 'available ' : 'False ' } , ... . , { 'pet ' : 'fish ' , 'price ' : '11.28 ' , 'available ' : 'True ' } ] l_2 = [ ( 'cat ' , '39.99 ' ... | How to transform a list of dicts into a list of tuples ? |
Python | I have the following listI used the following to remove the hyphenThe result I got The result that Ideally want isHow can I accomplish this in the most pythonic ( efficient way ) | list1= [ 'Dodd-Frank ' , 'insurance ' , 'regulation ' ] new1 = [ j.replace ( '- ' , ' ' ) for j in list1 ] new1= [ 'Dodd Frank ' , 'insurance ' , 'regulation ' ] new1= [ 'Dodd ' , 'Frank ' , 'insurance ' , 'regulation ' ] | How to split a compound word split by hyphen into two individual words |
Python | I 'm writing a small wrapper class around open that will filter out particular lines from a text file and then split them into name/value pairs before passing them back to the user . Naturally , this process lends itself to being implemented using generators.My `` file '' classUserland codeMy code , sadly , has two eno... | class special_file : def __init__ ( self , fname ) : self.fname = fname def __iter__ ( self ) : return self def __next__ ( self ) : return self.next ( ) def next ( self ) : with open ( self.fname , ' r ' ) as file : for line in file : line = line.strip ( ) if line == `` : continue name , value = line.split ( ) [ 0:2 ] ... | Custom generator for file filter |
Python | I have the following dataframe : My desired result is to have : Where the unique values found in df.id become column headers ( there can be several thousand of these ) , with their latitude and longitude as values.The closest I have come is using : But I know using any sort of iteration is bad in pandas ( and it 's now... | Timestamp id lat long0 665047 a 30.508420 -84.3728821 665047 b 30.491882 -84.3729382 2058714 b 30.492026 -84.3729383 665348 a 30.508420 -84.3728824 2055292 b 30.491899 -84.372938 Timestamp a b 0 665047 [ 30.508420 , -84.372882 ] [ 30.491882 , -84.372938 ] 1 665348 [ 30.508420 , -84.372882 ] NaN2 2055292 NaN [ 30.491899... | Create columns based on unique column values and fill |
Python | I have two data frames : df : Another data frame named allnames contains a list of names like this : I want to replace all the words in df that appear in allnames [ 'name ' ] with `` Firstname '' Expected output : I tried this : But it replaces almost 99 % of the words | id string_data1 My name is Jeff2 Hello , I am John3 I like Brad he is cool . id name1 Jeff2 Brad3 John4 Emily5 Ross id string_data1 My name is Firstname2 Hello , I am Firstname3 I like Firstname he is cool . nameList = '|'.join ( allnames [ 'name ' ] ) df [ 'string_data ' ] .str.replace ( nameList , `` FirstName '' , c... | How to replace a word in dataframe by using another dataframe in Pandas python |
Python | I was implementing binary search recursively in Python ( I know this is bad ) and got a max recursion error with the following code : I then changed my parameters and base case like so : This fixes the error , but I am not sure why . Can someone please explain ? | def bs_h ( items , key , lower , upper ) : if lower == upper : return None mid = ( lower + upper ) // 2 if key < items [ mid ] : return bs_h ( items , key , lower , mid ) else : return bs_h ( items , key , mid , upper ) def bs ( items , key ) : return bs_h ( items , key , 0 , len ( items ) -1 ) def bs_h ( items , key ,... | Could someone explain why this fixes my recursion error ? |
Python | Directory Structure : __init__ : Views : I hope someone can explain what I am doing wrong here -I guess I 'm not understanding how to properly import app . This results in a 404 . However when views is moved back to __init__ everything works properly . | from flask import flask app = Flask ( __name__ ) if __name__ == '__main__ ' app.run ( ) from app import app @ app.route ( '/ ' ) def hello_world ( ) : return 'Hello World ! ' | Why does my view function 404 ? |
Python | I 've got a list that contains the following : Now the ' 2/keys ' must be splitted . I figured it should be possible to make a list in a list ? But before splitting , I 've got to check if there 's a `` / '' at all.The following code , that obviously does n't work , is what I 've got : Is it possible to have an outcome... | x = [ ' 1 ' , ' 2/keys ' , ' 3 ' ] for numbers in x : if '/ ' in x : x [ numbers ] .split ( '/ ' ) x = [ ' 1 ' , [ ' 2 ' , 'keys ' ] , ' 3 ' ] | Splitting on / inside a list in Python |
Python | There is a code segment . running the program gets the following error The corresponding code segment is listed as follows . What can be the reason underlying it ? | epoch , step , d_train_feed_dict , g_train_feed_dict = inf_data_gen.next ( ) AttributeError : 'generator ' object has no attribute 'next ' inf_data_gen = self.inf_get_next_batch ( config ) def inf_get_next_batch ( self , config ) : `` '' '' Loop through batches for infinite epoches. `` '' '' if config.dataset == 'mnist... | Getting next item from generator fails |
Python | Extract numbers followed and preceded by words : it gives the list of all words and numbers in the gives q.so now i want method to get number along with words | String q = 'Consumer spending in the US rose to about 62 % of GDP in 1960 , where it stayed until about 1981 , and has since risen to 71 % in 2013 ' q = re.findall ( r'^ ( [ ^\d ] + ) \s ( \d+ ) \s* , \s* ( [ ^\d ] + ) \s ( \d+ ) ' , s ) | Extract number followed and preceded by the words |
Python | I need to decode a string 'a3b2 ' into 'aaabb ' . The problem is when the numbers are double , triple digits . E.g . 'a10b3 ' should detect that the number is not 1 but 10.I need to start accumulating digits.If I change the while loop to this : it does work but omits the last letter.I should not use regex , only loops ... | a = `` a12345t5i6o2r43e2 '' for i in range ( 0 , len ( a ) -1 ) : if a [ i ] .isdigit ( ) is False : # once i see a letter , i launch a while loop to check how long a digit streak # after it can be - it 's 2,3,4,5 digit number etc print ( a [ i ] ) current_digit_streak = `` counter = i+1 while a [ counter ] .isdigit ( ... | How do I accumulate a sequence of digits in a string and convert them to one number ? |
Python | I 'm trying to create a function that returns True is the string passed in is ' 1 ' ( valid ) or ' 1* ' ( valid ) or in the form of ' ( ' + valid + '| ' + valid + ' ) ' ( valid ) . What I mean by the last part is for example : ( 1|1 ) < - since its in the form of ' ( ' + valid + '| ' + valid + ' ) ' and ' 1 ' is valid ... | def check ( s ) : if s == ' 1 ' : return True elif s == ' 1'+'* ' : return True else : if s.startswith ( ' ( ' ) and s.endswith ( ' ) ' ) : # TO-DO pass return False check ( ' ( ( 1|1 ) |1 ) ' ) Truecheck ( ' ( ( 1|1* ) |1 ) ' ) Truecheck ( ' ( 1|1 ) ' ) Truecheck ( ' 1 ' ) Truecheck ( ' 1* ' ) Truecheck ( ' ( ( 1| ( 1... | Evaluating a string using recursion |
Python | I have two dataframes like thisI now want to populate columns prop1 and prop2 in df2 using the values of df1 . For each key , we will have more or equal rows in df1 than in df2 ( in the example above : 5 times A vs 3 times A , 2 times B vs 2 times B and 3 times C vs 1 time C ) . For each key , I want to fill df2 using ... | import pandas as pdimport numpy as npdf1 = pd.DataFrame ( { 'key ' : list ( 'AAABBCCAAC ' ) , 'prop1 ' : list ( 'xyzuuyxzzz ' ) , 'prop2 ' : list ( 'mnbnbbnnnn ' ) } ) df2 = pd.DataFrame ( { 'key ' : list ( 'ABBCAA ' ) , 'prop1 ' : [ np.nan ] * 6 , 'prop2 ' : [ np.nan ] * 6 , 'keep_me ' : [ 'stuff ' ] * 6 } ) key prop1... | How to populate columns of a dataframe using a subset of another dataframe ? |
Python | I have a class that keeps track of several other classes . Each of these other classes all need to access the value of a particular variable , and any one of these other classes must also be able to modify this particular variable such that all other classes can see the changed variable.I tried to accomplish this using... | class A : def __init__ ( self , state ) : self._b_obj = B ( self ) self._state = state @ property def state ( self ) : return self._state @ state.setter def state ( self , val ) : self._state = val @ property def b_obj ( self ) : return self._b_obj @ b_obj.setter def b_obj ( self , val ) : self._b_obj = valclass B : de... | Python Object Property Sharing |
Python | I have a table need to groupby by condition : When i use it gives me 13 Dm Ad 16 , which is like data being manipulated.The result I want is 13 Dm Af 16 , I know probably something wrong with 'name ' : 'first ' but how do i fix this please ? Thank you | R_num ORG name level13 Dm Ad 1713 Dm Af 16 df1=df.reset_index ( ) .groupby ( [ 'R_num ' , 'ORG ' ] ) .agg ( { 'name ' : 'first ' , 'level ' : [ 'min ' ] } ) | Get rows corresponding to the minimum with pandas groupby |
Python | Given some classifier ( SVC/Forest/NN/whatever ) is it safe to call .predict on the same instance concurrently from different threads ? From a distant point of view , my guess is they do not mutate any internal state . But I did not find anything in the docs about it.Here is a minimal example showing what I mean : | # ! /usr/bin/env python3import threadingfrom sklearn import datasetsfrom sklearn import svmfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.neural_network import MLPClassifierX , y = datasets.load_iris ( return_X_y=True ) # Some model . Might be any type , e.g . : clf = svm.SVC ( ) clf = RandomForestClas... | Are predictions on scikit-learn models thread-safe ? |
Python | Does Buildout support value substitution in the extends option of the buildout section ? For example , this example.cfg does n't extend with base.cfg : My goal is to send the file-to-extend as a parameter from the outside like this : I tried to merge the buildout : extends from the outside ; but that does n't work eith... | [ config ] base = base.cfg [ buildout ] extends = $ { config : base } parts = buildout -c example.cfg annotate buildout config : base=base.cfg -c example.cfg annotate buildout buildout : extends+=base.cfg -c example.cfg annotate | Does Buildout support value substitution in the extends option ? |
Python | I noticed some differences between the operations between x=x+a and x+=a when manipulating some numpy arrays in python.What I was trying to do is simply adding some random errors to an integer list , like this : but printing out x gives an integer list [ 0,1,2,3,4,5,6,7,8,9,10,11 ] .It turns out that if I use x=x+a ins... | x=numpy.arange ( 12 ) a=numpy.random.random ( size=12 ) x+=a | numpy data type casting behaves differently in x=x+a and x+=a |
Python | This is a basic example of what I 'm talking about : Count from 0 to 10000000Now with a sort of `` status '' of the computation ( displays percentage every 1 second ) : The first example takes 3.67188 seconds , the second example takes 12.62541 seconds . I guess that 's because the scripts has to continuously check if ... | import timek = 0beginning = time.time ( ) while k < 10000000 : k = k+1elapsed = round ( time.time ( ) -beginning , 5 ) print ( elapsed ) import timek = 0beginning = time.time ( ) interval = time.time ( ) while k < 10000000 : if time.time ( ) - interval > 1 : print ( round ( ( k/100000 ) , 5 ) ) interval = time.time ( )... | Python , calculating the status of computation slows down the computation itself |
Python | I 'm trying to get my programs memory footprint under control . I thought I 'd start with the imports , as I 'm only using 3-4 functions out of the rather large PyObjC library . However , I was a little surprised to see that importing specific pieces of a larger module had zero bearing on what was actually loaded into ... | Line # Mem usage Increment Line Contents================================================ 77 @ profile 78 7.953 MB 0.000 MB def test_import_all ( ) : 79 26.734 MB 18.781 MB import Quartz.CoreGraphics as CG Line # Mem usage Increment Line Contents================================================ 82 @ profile 83 7.941 MB 0... | When importing , why is the entire module loaded even when only specific portions are specified ? |
Python | I have a file encoded in a strange pattern . For example , Char ( 1 byte ) | Integer ( 4 bytes ) | Double ( 8 bytes ) | etc ... So far , I wrote the code below , but I have not been able to figure out why still shows garbage in the screen . Any help will be greatly appreciated . | BRK_File = 'commands.BRK'input = open ( BRK_File , `` rb '' ) rev = input.read ( 1 ) filesize = input.read ( 4 ) highpoint = input.read ( 8 ) which = input.read ( 1 ) print 'Revision : ' , rev print 'File size : ' , filesizeprint 'High point : ' , highpointprint 'Which : ' , whichwhile True opcode = input.read ( 1 ) pr... | File is not decoded properly |
Python | Suppose that I have a NumPy array of integers . And I have two arrays lower and upper , which represent lower and upper bounds respectively on slices of arr . These intervals are overlapping and variable-length , however lowers and uppers are both guaranteed to be non-decreasing . I want to find the min and the max of ... | arr = np.random.randint ( 0 , 1000 , 1000 ) lowers = np.array ( [ 0 , 5 , 132 , 358 , 566 , 822 ] ) uppers = np.array ( [ 45 , 93 , 189 , 533 , 800 , 923 ] ) out_arr = np.empty ( ( lowers.size , 2 ) ) for i in range ( lowers.size ) : arr_v = arr [ lowers [ i ] : uppers [ i ] ] out_arr [ i,0 ] = np.amin ( arr_v ) out_ar... | Vectorizing min and max of slices possible ? |
Python | I have very little C experience so this may be over my head , but I am curious as I am playing around with sys.getsizeof.I tried to look at the documentation but I only found this : getsizeof ( ) calls the object ’ s sizeof method and adds an additional garbage collector overhead if the object is managed by the garbage... | sys.getsizeof ( list ( range ( 10 ) ) ) # 200sys.getsizeof ( [ 0,1,2,3,4,5,6,7,8,9 ] ) # 144sys.getsizeof ( [ i for i in range ( 10 ) ] ) # 192 | Why is there a discrepancy in memory size with these 3 ways of creating a list ? |
Python | In a Python program which runs a for loop over a fixed range many times , e.g. , does it make sense to cache range : or will it not add much benefit ? | while some_clause : for i in range ( 0 , 1000 ) pass ... r = range ( 0 , 1000 ) while some_clause : for i in r pass ... | Is it worth caching Python 's range ( start , stop , step ) ? |
Python | I have the following dict : When the length of a group is smaller than a minimum size ( group_size=4 ) , I want to redistribute the members to the other groups . The result in this case would be something like : I have the following code , which works , but is less efficient than I 'd like : Important note : The real m... | groups = { `` group 1 '' : [ 1 , 2 , 3 , 4 ] , `` group 2 '' : [ 5 , 6 , 7 , 8 ] , `` group 3 '' : [ 9 , 10 , 11 , 12 ] , `` group 4 '' : [ 13 , 14 ] } groups = { `` group 1 '' : [ 1 , 2 , 3 , 4 , 13 ] , `` group 2 '' : [ 5 , 6 , 7 , 8 , 14 ] , `` group 3 '' : [ 9 , 10 , 11 , 12 ] } # Identify small groupssmall_groups ... | Redistribute dictionary value lists |
Python | I need a class that is an integer whose value can be changed after the object is created . I need this class to define a size that is first specified in millimeters . Later when the user-interface is created , I get a factor from the device-context that converts millimeters to pixels . This factor should change the mil... | class UiSize ( int ) : def __new__ ( cls , value=0 ) : i = int.__new__ ( cls , value ) i._orig_value = value return i def set_px_per_mm ( self , px_per_mm ) : pixel_value = int ( round ( self._orig_value * px_per_mm ) ) print `` pixel_value '' , pixel_value # how to set the new pixel_value to the object 's value ? s = ... | Integer object whose value can be changed after definition ? |
Python | NLTK version 3.4.5 . Python 3.7.4 . OSX version 10.14.5.Upgrading the codebase from 2.7 , started running into this issue just now . I 've done a fresh no-cache reinstall of all packages and extensions , in a fresh virtualenv . Pretty mystified as to how this could be happening to only me and I ca n't find anyone else ... | ( venv3 ) gmoss $ pythonPython 3.7.4 ( default , Sep 7 2019 , 18:27:02 ) [ Clang 10.0.1 ( clang-1001.0.46.4 ) ] on darwinType `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > import nltkTraceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > File `` /... | Getting `` bad escape '' when using nltk in py3 |
Python | Suppose an array a.shape == ( N , M ) and a vector v.shape == ( N , ) . The goal is to compute argmin of abs of v subtracted from every element of a - that is , I have a vectorized implementation via np.matlib.repmat , and it 's much faster , but takes O ( M*N^2 ) memory , unacceptable in practice . Computation 's stil... | out = np.zeros ( N , M ) for i in range ( N ) : for j in range ( M ) : out [ i , j ] = np.argmin ( np.abs ( a [ i , j ] - v ) ) | Efficient elementwise argmin of matrix-vector difference |
Python | I have two dictionaries items and u_itemsI want to update the items dictionary with u_items so I did this such that I can differentiate keys from both dictionariesOutput : but when i update the items dictionary with another dictionary , let 's say n_items , it replaces the value of B_1 instead of making it B_1_1output ... | items = { `` A '' : 1 , `` B '' : 2 , `` C '' : 3 } u_items = { `` D '' : 4 , `` B '' : 4 , `` E '' : 8 , `` C '' : 4 } items.update ( ( k + '_1 ' if k in items else k , v ) for k , v in u_items.items ( ) ) items = { ' A ' : 1 , ' B ' : 2 , ' C ' : 3 , 'D ' : 4 , 'B_1 ' : 4 , ' E ' : 8 , 'C_1 ' : 4 } n_items = { `` C '... | Combine two or more dictionaries with same keys |
Python | Can someone explain to me why I get < function < lambda > . < locals > . < lambda > at 0x0000000002127F28 > instead of 3 ? | > > > foo = True > > > bar = lambda x : x + 1 if foo else lambda x : x + 2 > > > bar ( 1 ) 2 > > > foo = False > > > bar = lambda x : x + 1 if foo else lambda x : x + 2 > > > bar ( 1 ) < function < lambda > . < locals > . < lambda > at 0x0000000002127F28 > # Hey ! ? WTF ? | Why does this lambda function act weirdly in an else statement ? |
Python | Following other posts here , I have a function that prints out information about a variable based on its name . I would like to move it into a module.Output : I would like to put this function oshape ( ) into a module so that it can be reused . However , placing in a module does not allow access to the globals from the... | # python 2.7import numpy as npdef oshape ( name ) : # output the name , type and shape/length of the input variable ( s ) # for array or list x=globals ( ) [ name ] if type ( x ) is np.array or type ( x ) is np.ndarray : print ( ' { :20 } { :25 } { } '.format ( name , repr ( type ( x ) ) , x.shape ) ) elif type ( x ) i... | Acessing a variable as a string in a module |
Python | Consider this exampleoutput : how can i get : | def dump ( value ) : print valueitems = [ ] for i in range ( 0 , 2 ) : items.append ( lambda : dump ( i ) ) for item in items : item ( ) 11 01 | lambda in python reference mind puzzle |
Python | Here is some code to demonstrate what I 'm talking about.I would expect both expressions to yield the exact same result , but the output of this program is : What am I not understanding here ? | class Foo ( tuple ) : def __init__ ( self , initialValue= ( 0,0 ) ) : super ( tuple , self ) .__init__ ( initialValue ) print Foo ( ) print Foo ( ( 0 , 0 ) ) ( ) ( 0 , 0 ) | Python ignores default values of arguments supplied to tuple in inherited class |
Python | I have a dataframe which looks like this : I wish to add additional columns , such as 'flag_1 ' & 'flag_2 ' below , which allow myself ( and other when I pass on the amended data ) to filter easily.Flag_1 is an indication of the first appearance of that customer in the data set . I have implemented this successfully by... | customer_id event_date data 1 2012-10-18 0 1 2012-10-12 0 1 2015-10-12 0 2 2012-09-02 0 2 2013-09-12 1 3 2010-10-21 0 3 2013-11-08 0 3 2013-12-07 1 3 2015-09-12 1 customer_id event_date data flag_1 flag_21 2012-10-18 0 1 01 2012-10-12 0 0 01 2015-10-12 0 0 02 2012-09-02 0 1 02 2013-09-12 1 0 13 2010-10-21 0 1 03 2013-1... | pandas : finding first incidences of events in df based on column values and marking as new column values |
Python | Suppose I want a class named Num which contains a number , its half , and its square.I should be able to modify any of the three variables and it will affects all of its related member variables . I should be able to instantiate the class with any of the three value.What is the best way to design this class so that it ... | num = Num ( 5 ) print num.n , num.half , num.square num = Num ( half=2.5 ) print num.n , num.half , num.square num.square = 100print num.n , num.half , num.square | How to design a class containing related member variables efficiently ? |
Python | I have been working on a project that is using Google App Engine 's python sdk . I was digging around in it and saw a lot of methods like this.Is there any reason they assign the private variable like this ? I mean I do n't see the point of defining a method as private and then assigning it to a non private variable . ... | def _put ( self , bla , bla ) : do somethingput = _put def put ( self , bla , bla ) : do something | Assigning variable to private method |
Python | Is there a convenient way to merge two dataframes with respect to the distance between rows ? For the following example , I want to get the color for df1 rows from the closest df2 rows . The distance should be computed as ( ( x1-x2 ) **0.5+ ( y1-y2 ) **0.5 ) **0.5 . | import pandas as pddf1 = pd.DataFrame ( { ' x ' : [ 50,16,72,61,95,47 ] , ' y ' : [ 14,22,11,45,58,56 ] , 'size ' : [ 1,4,3,7,6,5 ] } ) df2 = pd.DataFrame ( { ' x ' : [ 10,21,64,31,25,55 ] , ' y ' : [ 54,76,68,24,34,19 ] , 'color ' : [ 'red ' , 'green ' , 'blue ' , 'white ' , 'brown ' , 'black ' ] } ) | merging pandas dataframes with respect to a function output |
Python | Say I have a DataFrameI want to grab row 2 , 5 , 6 and 10 because these are the last row for each value in Column 1 . Let 's say Column 1 is an ID and Column 2 indicates the number of that ID . I need it to pick the maximum number in Column 2 for each number in Column 1 and keep Column 3 without changing Column 2 and 3... | data = { 'Column 1 ' : [ 1 , 1 , 2 , 2 , 2 , 3 , 4 , 4 , 4 , 4 ] , 'Column 2 ' : [ 1 , 2 , 1 , 2 , 3 , 1 , 1 , 2 , 3 , 4 ] , 'Column 3 ' : [ 1 , 2 , 1 , 4 , 3 , 6 , 1 , 2 , 7 , 5 ] } df = pd.DataFrame ( data=data ) 1 1 11 2 22 1 12 2 42 3 33 1 64 1 14 2 24 3 74 4 5 1 2 22 3 33 1 64 4 5 df.groupby ( [ 'Column 1 ' ] ) .m... | Is there a way to grab the last item of a group |
Python | I want to take in a list of strings and sort them by the occurrence of a character using the python function sort ( ) or sorted ( ) . I can do it in many lines of code where I write my own sort function , I 'm just unsure about how to do it so easily in pythonIn terms of sorted ( ) it can take in the list and the keyTh... | l = [ ' a ' , 'wq ' , 'abababaaa ' ] # I think it 's something like this , I know I 'm missing somethingsorted ( l , key = count ( ' a ' ) ) [ 'wq ' , ' a ' , 'abababaaa ' ] | Sorting a list based on the occurrence of a character |
Python | I want to do this : There 's no problem if I hard code fileName . But I need to it with fileName as a string variable and that does n't seem to work . The context of the question is that I 'm trying to make a function that has the file name as an argument . The function imports variableName from whichever file is given... | from fileName import variableName data = [ xxxxx ] | how do I import from a file if I do n't know the file name until run time ? |
Python | While following a C extension for Python tutorial , my module seems to missing its contents . While building and importing the module have no problem , using the function in the module fails . I am using Python 3.7 on macOS.testmodule.csetup.pyThe test and error are | # define PY_SSIZE_T_CLEAN # include < Python.h > static PyObject* add ( PyObject *self , PyObject *args ) { const long long x , y ; if ( ! PyArg_ParseTuple ( args , `` LL '' , & x , & y ) ) { return NULL ; } return PyLong_FromLongLong ( x + y ) ; } static PyMethodDef TestMethods [ ] = { { `` add '' , add , METH_VARARGS... | Python C Extension Missing Function |
Python | In one example of Sage math ( search for octahedral ) there is this line : What does this . < v > do ? | K. < v > = sage.groups.matrix_gps.finitely_generated.CyclotomicField ( 10 ) | K. < v > notation in Python 2 |
Python | I am working on a problem where I am using a nested groupby.apply on a pandas DataFrame . During the first apply I am adding a column that I am using for the second inner groupby.apply . The combined result looks faulty to me . Can anyone explain to me why the below phenomen happens and how to reliably fix it ? Here is... | import numpy as npimport pandas as pdT = np.array ( [ [ 1,1,1 ] , [ 1,1,1 ] , [ 1,2,2 ] , [ 1,2,2 ] , [ 2,1,3 ] , [ 2,1,3 ] , [ 2,2,4 ] , [ 2,2,4 ] , ] ) df = pd.DataFrame ( T , columns= [ ' a ' , ' b ' , ' c ' ] ) print ( df ) def foo2 ( x ) : return xdef foo ( x ) : print ( `` * '' * 80 ) # Add column d and groupby/a... | Pandas nested groupby gives unexpected results |
Python | I have two sorted lists containing float values . The first contains the values I am interested in ( l1 ) and the second list contains values I want to search ( l2 ) . However , I am not looking for exact matches and I am tolerating differences based on a function . Since I have do this search very often ( > > 100000 )... | # check if two floats are close enough to matchdef matching ( mz1 , mz2 ) : if abs ( ( 1-mz1/mz2 ) * 1000000 ) < = 2 : return True return False # imagine another huge for loop around everythingl1 = [ 132.0317 , 132.8677 , 132.8862 , 133.5852 , 133.7507 ] l2 = [ 132.0317 , 132.0318 , 132.8678 , 132.8861 , 132.8862 , 133... | Matching two lists containing slightly differing float values by allowing a tolerance |
Python | I was just toying around with an idea , and I could n't think of a way to resolve this in the backend without daunting security issues.Say I want to give users the opportunity to create simple algorithms via a webservice and test these over small lists , e.g . range ( 0 , 5 ) then report back the results back via anoth... | class Algorithm ( whatever ) : function = whatever.CharField ( max_length=75 ) ' f ( x ) =x+ ( x/5 ) **0.75 ' | Evaluating algorithms from 'untrusted ' users |
Python | I want to merge rows of dataframe with one common column value and then merge rest of the column values separated by comma for string values and convert to array/list for int values.Expecting result like : I can use groupby for column D but how can I use apply for columns A , C as apply ( np.array ) and apply ( ' , '.j... | A B C D1 one 100 value4 four 400 value5 five 500 value2 two 200 value A B C D [ 1,4,5,2 ] one , four , five , two [ 100,400,500,200 ] value | How to merge rows in dataframe with different columns ? |
Python | The trouble is this . Lets say we have a pandas df that can be generated using the following : then let 's suppose we would like a count of each category by month . so we go and do something like But what we 'd like to see is : Where the difference is categories that did not show up in a particular month would still sh... | month= [ 'dec ' , 'dec ' , 'dec ' , 'jan ' , 'feb ' , 'feb ' , 'mar ' , 'mar ' ] category = [ ' a ' , ' a ' , ' b ' , ' b ' , ' a ' , ' b ' , ' b ' , ' b ' ] sales= [ 1,10,2,5,12,4,3,1 ] df = pd.DataFrame ( list ( zip ( month , category , sales ) ) , columns = [ 'month ' , 'cat ' , 'sales ' ] ) print ( df ) | month cat... | Return aggregate for all unique in a group |
Python | prints val , key , i.e . the value is evaluated first . Is this behaviourconsistent across python versions and implementations ? documented anywhere ? ( http : //docs.python.org/2/reference/expressions.html # dictionary-displays says nothing ) | def key ( ) : print 'key'def val ( ) : print 'val ' { key ( ) : val ( ) } | Evaluation order of dictionary literals |
Python | I 've tried to solve my issue but I could not . I have three Python lists : My problem is to generate a Python dictionary based on the combination of those three lists : The desired output : | atr = [ ' a ' , ' b ' , ' c ' ] m = [ ' h ' , ' i ' , ' j ' ] func = [ ' x ' , ' y ' , ' z ' ] py_dict = { ' a ' : [ ( ' x ' , ' h ' ) , ( ' x ' , ' i ' ) , ( ' x ' , ' j ' ) , ( ' y ' , ' h ' ) , ( ' y ' , ' i ' ) , ( ' y ' , ' j ' ) , ( ' z ' , ' h ' ) , ( ' z ' , ' i ' ) , ( ' z ' , ' j ' ) ] , ' b ' : [ ( ' x ' , '... | Generate Python dictionary from combination of lists |
Python | I 've got dictionaries such as : I am trying to make it so that the program can find the shortest substring in the list ( such as GAA in the first ) and use it to find all other entries that are simply extensions of GAA ( strings that start with GAA and just have extra letters ) and removes them.I know there 's been pl... | ' 1 ' : [ 'GAA ' , 'GAAA ' , 'GAAAA ' , 'GAAAAA ' , 'GAAAAAG ' , 'GAAAAAGU ' , 'GAAAAAGUA ' , 'GAAAAAGUAU ' , 'GAAAAAGUAUG ' , 'GAAAAAGUAUGC ' , 'GAAAAAGUAUGCA ' , 'GAAAAAGUAUGCAA ' , 'GAAAAAGUAUGCAAG ' , 'GAAAAAGUAUGCAAGA ' , 'GAAAAAGUAUGCAAGAA ' , 'GAAAAAGUAUGCAAGAAC ' ] ' 2 ' : [ 'GAG ' , 'GAGA ' , 'GAGAG ' , 'GAGAG... | Removing all extension of a string in list |
Python | So I have strings that includes names and sometime a username in a string followed by a datetime stampI want to extract the usernames from this string.I have tried different regex patterns the closest I came to extract was followingUsing the following regex pattern | GN1RLWFH0546-2020-04-10-18-09-52-563945.txtJOHN-DOE-2020-04-10-18-09-52-563946t64.txtDESKTOP-OHK45JO-2020-04-09-02-27-11-451975.txt GN1RLWFH0546JOHN-DOE DESKTOP-OHK45JO GN1RLWFH0546DESKTOPJOHN names = re.search ( r '' \ ( ? ( [ 0-9A-Za-z ] + ) \ ) ? `` , agent_str ) print ( names.group ( 1 ) ) | Regex to extract usernames/names from a string |
Python | I have 3 lists and I want to find the difference between the 1st/2nd and 2nd/3rd and print them . Here is my code : but i get only 3 as output.How to make it output 1 and 3 ? I tried using sets as well , but it only printed 3 again . | n1 = [ 1,1,1,2,3 ] n2 = [ 1,1,1,2 ] # Here the 3 is not found ( `` 3 '' is not present in n1 at all ) n3 = [ 1,1,2 ] # here 1 is not found ( there are fewer `` 1 '' s in n3 than in n2 ) for x in n1 : if x not in n2 : print x for m in n2 : if m not in n3 : print m | How to find the difference between 3 lists that may have duplicate numbers |
Python | I am writing a Java collection class that is meant to be used with Jython . I want end users to be able to manipulate the collection this way : What I find in the Python documentation is the following methods : __getitem__ and __setitem__ methods should do the job for bracket operator overloading.__iadd__ method is the... | myCollection = MyJavaCollection ( ) myCollection [ 0 ] += 10. ; a = myCollection [ 0 ] ; //a = 10myCollection [ 0 ] += 20. ; b = myCollection [ 0 ] ; //b = 20 | Overload instance [ key ] += val |
Python | I 'm using Python 3.8.5 . I 'm trying to write a short script that concatenates PDF files and learning from this Stack Overflow question , I 'm trying to use PyPDF2 . Unfortunately , I ca n't seem to even create a PyPDF2.PdfFileReader instance without crashing.My code looks like this : When I try to run it , I get the ... | import pathlibimport PyPDF2pdf_path = pathlib.Path ( ' 1.pdf ' ) with pdf_path.open ( 'rb ' ) as pdf_file : reader = PyPDF2.PdfFileReader ( pdf_file , strict=False ) Traceback ( most recent call last ) : File `` C : \ ... \pdf\open_pdf.py '' , line 6 , in < module > reader = PyPDF2.PdfFileReader ( pdf_file , strict=Fal... | Ca n't open PDF file with PyPDF2 |
Python | How can I write the following code more concisely ? I know this can be written in one or two lines without using append , but I 'm a Python newbie . | scores = [ ] for f in glob.glob ( path ) : score = read_score ( f , Normalize = True ) scores.append ( score ) | Pythonic and concise way to construct this list ? |
Python | Any idea if it 's possible to shorten and prettify this one ( an extra variant assumes nested if-else conditions and more lists ) ? | some_list , some_other_list = [ ] , [ ] if condition : some_list.append ( value ) else : some_other_list.append ( value ) | How to shorten appending to different lists depending on the outcome of if statement |
Python | Let 's say I have the the following dataframe ( although the one I 'm actually working with is over 100 rows ) : For each row , I want to : In col= [ ' b ' , ' c ' , 'd ' ] , find rows where there is more than one column with value = 1 . This is my condition.Duplicate rows that meet the above condition should be duplic... | > > df a b c d etitle0 1 0 0 string title1 0 1 1 string > > dfa b c d etitle0 1 0 0 string title1 0 1 0 string title1 0 0 1 string | Duplicating rows sequentially based on sum of multiple columns |
Python | I 've got two DataFrames , containing the same information ( length , width ) about different aspects ( left foot , right foot ) of the same objects ( people ) .I want to merge these into a single DataFrame , so I do this : Working with suffixes is cumbersome however . I would instead like the columns to be a MultiInde... | import pandas as pdleft_feet = pd.DataFrame ( data= { `` Length '' : [ 20 , 30 , 25 ] , `` Width '' : [ 8 , 10 , 9 ] } , index= [ 0 , 1 , 2 ] ) right_feet = pd.DataFrame ( data= { `` Length '' : [ 24 , 30 ] , `` Width '' : [ 8 , 10 ] } , index= [ 2 , 1 ] ) print ( left_feet ) Length Width0 20 81 30 102 25 9print ( righ... | Pandas merge with MultiIndex for repeated columns |
Python | Currently I am doing this in my code : Then at the top of my main scripts I do this : Problem is that there are too many messages . Is there any way to restrict it to one or a few different loggers ? | logger = logging.getLogger ( __name__ ) logger.info ( `` something happened '' ) logging.basicConfig ( level=logging.INFO ) | How do I print out only log messages for a given logger ? |
Python | I 'd like to use some generator expressions as attributes for some expensive computation of data . If possible I would like to be able to do something like this : I would liked to have seen this print out 2 4 6 8 but this gives no output . Have I made some sort of simple mistake here ? Is what I am trying to do here po... | class Test : def __init__ ( self ) : self.data = [ ] self.evens = ( i for i in self.data if i % 2 == 0 ) def __main__ ( ) : t = Test ( ) t.data = [ 1,2,3,4,5,6,7,8 ] for item in t.evens : print ( item ) if __name__ == '__main__ ' : __main__ ( ) | Generator expression in class not producing output I expect |
Python | I am trying to stick to Google 's styleguide to strive for consistency from the beginning . I am currently creating a module and within this module I have a class . I want to provide some sensible default values for different standard use cases . However , I want to give the user the flexibility to override any of the ... | MY_DEFAULTS = { `` use_case_1 '' : { `` x '' : 1 , `` y '' : 2 } , `` use_case_2 '' : { `` x '' : 4 , `` y '' : 3 } } class MyClass : def __init__ ( self , use_case = None , x = None , y = None ) : self.x = x self.y = y if use_case : if not self.x : self.x = MY_DEFAULTS [ use_case ] [ `` x '' ] if not self.y : self.y =... | Most pythonic way to provide defaults for class constructor |
Python | This is my table : Now , I want to group all rows by Column A and B . Column C should be summed and for column E , I want to use the value where value C is max.I did the first part of grouping A and B and summing C. I did this with : But at this point , I am not sure how to tell that column E should take the value wher... | A B C E0 1 1 5 41 1 1 1 12 3 3 8 2 df = df.groupby ( [ ' A ' , ' B ' ] ) [ ' C ' ] .sum ( ) A B C E0 1 1 6 41 3 3 8 2 | df.groupby ( ) modification HELP needed |
Python | I have a df : And it looks like this : I wish to create a new dataframe for each ID ( person 's name ) that either one column contains number 78 within the group ( no matter 78 appears in From_num or To_num or both ) , and remove the person BOTH columns does n't contain 78 , in this case 'Park ' . I have wrote code lik... | df2 = pd.DataFrame ( { 'ID ' : [ 'James ' , 'James ' , 'James ' , 'Max ' , 'Max ' , 'Max ' , 'Max ' , 'Max ' , 'Park ' , 'Park ' , 'Park ' , 'Tom ' , 'Tom ' , 'Tom ' , 'Tom ' ] , 'From_num ' : [ 78 , 420 , 'Started ' , 298 , 78 , 36 , 298 , 'Started ' , 28 , 311 , 'Started ' , 60 , 520 , 99 , 'Started ' ] , 'To_num ' :... | Pandas : create a new df from another df contains specific value within group |
Python | I have a text document with 32 articles in it and I want to spot each article 's date . I have observed that the date comes on the 5th row of each article . So far I have split the text into the 32 articles using : I will like to create a list that contains the date for each article , MONTH and YEAR only : As it can be... | import re sections = [ ] current = [ ] with open ( `` Aberdeen2005.txt '' ) as f : for line in f : if re.search ( r '' ( ? i ) \d+ of \d+ DOCUMENTS '' , line ) : sections.append ( `` '' .join ( current ) ) current = [ line ] else : current.append ( line ) print ( len ( sections ) ) | Date list in text |
Python | I 'm having trouble assigning the assignment operator.I have successfully overloaded __setattr__ . But after the object is initialized , I want __setattr__ to do something else , so I try assigning it to be another function , __setattr2__.Code : What I get : What I want/expect : | class C ( object ) : def __init__ ( self ) : self.x = 0 self.__setattr__ = self.__setattr2__ def __setattr__ ( self , name , value ) : print `` first , setting '' , name object.__setattr__ ( self , name , value ) def __setattr2__ ( self , name , value ) : print `` second , setting '' , name object.__setattr__ ( self , ... | Trouble with assigning ( or re-overloading ) the assignment operator in Python |
Python | I have two images of resolution 4095x4095 and every pixel has a different color ( no duplicate pixels within one image ) . I am trying to build a `` map '' describing the movement of each pixel between the two images.What I have now is a working , but very naive algorithm , that simply loops through all pixels until it... | import PILimport timefrom PIL import Imageraw = Image.open ( 'image1.png ' ) rawLoad = raw.load ( ) rendered = Image.open ( 'image2.png ' ) renderedLoad = rendered.load ( ) counter = 1timer = time.time ( ) for rendered_x in range ( rendered.width ) : for rendered_y in range ( rendered.height ) : for raw_x in range ( ra... | Use numpy to quickly iterate over pixels |
Python | I know how to get the date : But is there a way where you can work out the days/hours until a certain date , maybe storing the date as an integer or something ? Thx for all answers | from datetime import datetimetime = datetime.now ( ) print ( time ) | Can you do sums with a datetime in Python ? |
Python | I have the following piece of code . In this , I want to make use of the optional parameter given to ' a ' ; i.e ' 5 ' , and not ' 1 ' . How do I make the tuple 'numbers ' contain the first element to be 1 and not 2 ? | def fun_varargs ( a=5 , *numbers , **dict ) : print ( `` Value of a is '' , a ) for i in numbers : print ( `` Value of i is '' , i ) for i , j in dict.items ( ) : print ( `` The value of i and j are : '' , i , j ) fun_varargs ( 1,2,3,4,5,6,7,8,9,10 , Jack=111 , John=222 , Tom=333 ) | Using default arguments in a function with variable arguments . Is this possible ? |
Python | I 'm working on building a python library for manipulating the lighting and programmability features of my cheap Chinese iGK64 mechanical keyboard , because the Windows driver app does n't work on Linux.I 've run the manufacturer 's driver app in a Windows VM and captured USB packets for analysis . Over the last couple... | reg : 0x22 instr : 0x02 addr : 0x0000 len : 56 ( 0x3800 ) sum : 0xE670payload : 0xFFFFFFFFFFFFFFFF010000020200000204000002080000021000000220000002FFFFFFFFFFFFFFFF00040002000500020006000200070002 reg : 0x21 instr : 0x02 addr : 0x0100 len : 00 ( 0x0000 ) sum : 0xB63Dpayload : 0x0000000000000000000000000000000000000000000... | What checksum algorithm do to these packets use ? |
Python | Get this simple python code , same matching with re.compile instance.I noticed that even though I am using the very same value , it creates two instances , and repeats them accordingly.I wonder if one can tell the reason for this behavior , Why does it create the second instance at all ? Why only two ? And why each tim... | > > > import re > > > > > > rec = re.compile ( `` ( ? : [ -a-z0-9 ] +\. ) + [ a-z ] { 2,6 } ( ? : \s| $ ) '' ) > > > > > > rec.match ( 'www.example.com ' ) < _sre.SRE_Match object at 0x23cb238 > > > > rec.match ( 'www.example.com ' ) < _sre.SRE_Match object at 0x23cb1d0 > > > > rec.match ( 'www.example.com ' ) < _sre.S... | What is the reason python handles locals ( ) this way ( in pairs ) ? |
Python | Is the following safe ? Does the list comprehension evaluate first , creating a new list , and then assign that new list to x ? I was told once that changing a list while iterating over it is an unsafe operation . | x = [ 1 , 2 , 3 , 4 ] x = [ y+5 for y in x ] | Is it safe to assign list comprehension to the original list ? |
Python | I am working in Python . The dictionary I have looks like this : And I need to order it like this : Where the sub-dictionary with the greatest combination of exclusive key values is in the first element , the second greatest combination of exclusive key values is in the second element and so forth . The greatest combin... | score = { ' a ' : { 4 : ' c ' , 3 : 'd ' } , ' b ' : { 6 : ' c ' , 3 : 'd ' } } rank = [ { a:3 , b:6 } , { a:4 , b:3 } ] | How can I get a ranked list from a dictionary ? |
Python | I am trying to run a forward pass on a convolutional neural network having a convolutional layer , followed by a pooling layer and finally a rectified linear unit ( ReLU ) activation layer . The details about input data and convolutional layer filters are as follows : X : 4-dimensional input data having shape [ N , H ,... | import numpy as npimport tensorflow as tfX = np.random.random ( [ 60000 , 32 , 32 , 1 ] ) W = np.random.random ( [ 3 , 3 , 1 , 6 ] ) C = tf.nn.conv2d ( X , W , strides= [ 1,1,1,1 ] , padding= '' VALID '' ) P = tf.nn.avg_pool ( C , ksize= [ 1,2,2,1 ] , strides= [ 1,2,2,1 ] , padding= '' VALID '' ) A = tf.nn.relu ( P ) w... | Tensorflow Placeholders vs Tensorflow Constants vs Numpy Arrays |
Python | I have trained two separate modelsModelA : Checks if the input text is related to my work ( Binary Classifier [ related/not-related ] ) ModelB : Classifier of related texts ( Classifier [ good/normal/bad ] ) . Only the related texts are relayed to this model from ModelAI wantModelC : Ensemble classifier that outputs [ ... | # Output of modelA will be a vector I presume ` ( 1 , None ) ` where ` None ` is batchdef ModelC.predict ( input ) : outputA = ModelA ( input ) if outputA == 'not-related ' : return outputA return ModelB ( outputA ) | Keras vertical ensemble model with condition in between |
Python | I seem to be running into a bug with Python 's built-in sorted function . I ca n't seem to find it documented or described anywhere , but I 'm also getting results that seem to be inherently impossible based on my understanding of Python so I 'm hoping that someone can help , or at least point me in the right direction... | sorted_values = sorted ( all_values ) top_250 = [ item for item in sorted_values if item < sorted_values [ 250 ] ] len ( top_250 ) # 5828 [ 4.8502882289326867e-14 , 8.820403952763587e-14 , 1.0250590153123516e-13 , 1.6954166246183968e-13 , 1.908753789966549e-13 , 2.004836996365545e-13 , 3.5909784960471013e-13 , 5.166693... | sorted ( ) function differing from results obtained via list comprehension |
Python | ContextI am trying to create a program that gets the product of all n pairs in a number reading from left to rightFor example , in the number 2345678 : The product of all 2 pairs would be 2*3 = 6 , 3*4=12 , 4*5=20 , 5*6=30 etc ... The product of all 3 pairs would be 2*3*4=24,3*4*5=60 , 4*5*6=120 etc ... I have complete... | num = 2345678num = str ( num ) n = 2start_pos = 0for i in range ( start_pos , len ( num ) ) : try : x += 1 t = int ( num [ i ] ) * int ( num [ i+1 ] ) # hardcoded for n = 2 print ( t ) start_pos += 1 except IndexError : break | Change length of operation depending on a value |
Python | I have a python class , and I need to add an arbitrary number of arbitrarily long lists to it . The names of the lists I need to add are also arbitrary . For example , in PHP , I would do this : How do I do this in Python ? I 'm also wondering if this is a reasonable thing to do . The alternative would be to create a d... | class MyClass { } $ c = new MyClass ( ) ; $ n = `` hello '' $ c. $ n = array ( 1 , 2 , 3 ) ; | Adding variably named fields to Python classes |
Python | How can I make a string output a list ? ( Probably very simple , I know ) I have looked through all of google , and NONE of the solutions worked.My code : ( it 's a bit paraphrased ) Outputs : file1.txt file2.txt file3.txt in the Pmw.ScrolledText box.What do I need to do to make the output look like the following ? My ... | import Pmwfrom tkinter import *root = Tk ( ) console = Pmw.ScrolledText ( ... some arguments ... ) console.pack ( ... some arguments ... ) console.settext ( os.listdir ( `` . `` ) ) root.mainloop ( ) file1.txtfile2.txtfile3.txt | Make a string output as a list in Pwm |
Python | I try to find way for update speсial software ( Python application ) on client.Client already have HG or GIT , and I can dictate any requirements for client environment.But client have slowly and breaking out internet connection.HG , GIT and others tools ideal for update procedure by changesets with minimal traffic ban... | wget -c https : //repo.myserver.com/bundle ? from=rev1 & to=rev2 | Any ways to resuming download on HG or GIT changsets pulling ? |
Python | Given an arbitrary string ( i.e. , not based on a pattern ) , say : I am trying to partition a string based a list of indexes.Here is what I tried , which does work : The split is based on a list of indexes [ 3,10,12,40 ] . This list then needs to be transformed into a list of start , end pairs like [ [ 0 , 3 ] , [ 3 ,... | > > > string.ascii_letters'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ' import stringdef split_at_idx ( txt , idx ) : new_li= [ None ] *2*len ( idx ) new_li [ 0 : :2 ] =idx new_li [ 1 : :2 ] = [ e for e in idx ] new_li= [ 0 ] +new_li+ [ len ( txt ) ] new_li= [ new_li [ i : i+2 ] for i in range ( 0 , len ( new... | Efficiently partition a string at arbitrary index |
Python | I know I 'm close to figuring this out but I 've been wracking my brain and ca n't think of what 's going wrong here . I need to count the number of vowels in the array of nameList using the vowelList array , and currently it 's outputting 22 , which is not the correct number of vowels.Incidentally , 22 is double the l... | nameList = [ `` Euclid '' , `` Archimedes '' , `` Newton '' , '' Descartes '' , `` Fermat '' , `` Turing '' , `` Euler '' , `` Einstein '' , `` Boole '' , `` Fibonacci '' , `` Nash '' ] vowelList = [ ' A ' , ' a ' , ' E ' , ' e ' , ' I ' , ' i ' , ' O ' , ' o ' , ' U ' , ' u ' ] z=0counter = 0for k in nameList : i = 0 ... | Counting vowels in an array |
Python | Consider this simple class : Now if I create two instances of the class and compare their 'method ' attributes , I get different results in Python 3.7 and 3.8 : What 's going on here ? Why are the methods equal in 3.7 but not in 3.8 ? And what does this have to do with __eq__ ? | class A : def method ( self ) : pass def __eq__ ( self , other ) : return True meth1 = A ( ) .methodmeth2 = A ( ) .methodprint ( meth1 == meth2 ) # True in 3.7 , False in 3.8 | Comparing object methods leads to different results in 3.8 |
Python | I have these lists : How can I split l1 this way ? I 've tried using a function : But it 's not working ... | l1 = [ a , b , c , d , e , f , g , h , i ] l2 = [ 1,3,2,3 ] [ [ a ] , [ b , c , d ] , [ e , f ] , [ g , h , i ] ] -The first element is a list of one element because of the 1 of l2-The second element is a list of three elements because of the 3 of l2-The third element is a list of two elements because of the 2 of l2-Th... | Splitting a list to sublists with sizes given in another list |
Python | I was wondering if someone could explain why these two examples ultimately yield the same result : and : I intuitively understand the first 'if ... is None ' but I struggle with the second example . Are both ok to use ? I realise this could be quite an easy question hence if anyone could direct me to any reading that w... | class Myclass ( ) : def __init__ ( self , parameter=None ) if parameter is None : self.parameter = 1.0 else : self.parameter = parameter class Myclass ( ) : def __init__ ( self , parameter=None ) if parameter : self.parameter = parameter else : self.parameter = 1.0 | python class default parameter |
Python | I have the perl regular expression /VA=\d+ : ( \S+ ) : ENSG/ which is used in a if statement asI am trying to figure out what the best way to replicate this in python would be . Right now I haveIs this a good way to translate it ? I guess this is one area where perl is actually more readable than python.Note that the p... | if ( $ info =~ /VA=\d+ : ( \S+ ) : ENSG/ ) { $ gene = $ 1 ; gene_re = re.compile ( r'VA=\d+ : ( \S+ ) : ENSG ' ) this_re = re.search ( gene_re , info ) if this_re is not None : gene = info [ this_re.start ( 0 ) : this_re.end ( 0 ) ] | Which python re module to pick for translating a perl regular expression |
Python | I created a javaFX chooser file in Jython . It was n't easy to port from Java to Jython , but in the end some results came . Now I would like to parameterize the obtained class , taking into account the file filters , so as to be able to use the object for browsing different from the type of filtered files.I tried to i... | import sysfrom javafx.application import Applicationfrom javafx.stage import FileChooser , Stageclass fileBrowser ( Application ) : @ classmethod def main ( cls , args ) : fileBrowser.launch ( cls , args ) def start ( self , primaryStage ) : fc = FileChooser ( ) filter = FileChooser.ExtensionFilter ( `` All Images '' ,... | Add file filters to JavaFx Filechooser in Jython and parametrize them |
Python | I have a Python package called Util . It includes a bunch of files . Here is the include statements on top of one of the files in there : This works fine when I run my unit tests.When I install Util in a virtual environment in another package everything breaks . I will need to change the import statements to and then e... | from config_util import ConfigUtil # ConfigUtil is a class inside the config_util moduleimport error_helper as eh from Util.config_util import ConfigUtilfrom Util import error_helper as eh | is there any point in using relative paths in Python import statement ? |
Python | I am trying to read in a Fuzzy plain text rule and pass the parameters to a SciKit-Fuzzy function call to create fuzzy rules.For example , if I read in this text rule : Then the function call will be : If text rule is : Then the function call will be : Since each rule can have unlimited number of input variables , e.g ... | IF service IS poor OR food IS rancid THEN tip IS cheap ctrl.Rule ( service [ 'poor ' ] | food [ 'rancid ' ] , tip [ 'cheap ' ] ) IF service IS good THEN tip IS average ; ctrl.Rule ( service [ 'good ' ] , tip [ 'average ' ] ) IF service IS good AND food IS good AND mood IS happy THEN tip IS high | Calling a function with unknown number of parameters Python |
Python | A colleague of mine mistakenly typed this ( simplified ) code , and was wondering why his exception was n't getting caught : Now I know that the correct syntax to catch both types of exception should be except ( IndexError , ValueError ) : , but why is the above considered valid syntax ? And how does it work ? For exam... | > > > try : ... raise ValueError ... except IndexError or ValueError : ... print 'Caught ! ' ... Traceback ( most recent call last ) : File `` < stdin > '' , line 2 , in < module > ValueError > > > try : ... raise IndexError ... except IndexError or ValueError : ... print 'Caught ! ' ... Caught ! | Explanation of 'or ' in exception syntax , why is it valid syntax and how does it work ? |
Python | I am confused why FooBar.__mro__ does n't show < class '__main__.Parent ' > like the above two.I still do n't know why after some digging into the CPython source code . | from typing import NamedTuplefrom collections import namedtupleA = namedtuple ( ' A ' , [ 'test ' ] ) class B ( NamedTuple ) : test : strclass Parent : passclass Foo ( Parent , A ) : passclass Bar ( Parent , B ) : passclass FooBar ( Parent , NamedTuple ) : passprint ( Foo.__mro__ ) # prints ( < class '__main__.Foo ' > ... | Weird MRO result when inheriting directly from typing.NamedTuple |
Python | I searched and I could n't find a problem like mine . So if there is and somehow I could n't find please let me know . So I can delete this post.I stuck with a problem to split pandas dataframe into different data frames ( df ) by a value . I have a dataset inside a text file and I store them as pandas dataframe that h... | In [ 8 ] : dfOut [ 8 ] : var10 a1 b2 c3 d4 endValue5 h6 f7 b8 w9 endValue var1 { [ 0 a1 b2 c3 d4 endValue ] } , { [ 0 h1 f2 b3 w4 endValue ] } | Split Pandas Dataframe Column According To a Value |
Python | From a segmentation mask , I am trying to retrieve what labels are being represented in the mask . This is the image I am running through a semantic segmentation model in AWS Sagemaker.Code for making prediction and displaying mask.This image is the segmentation mask that was created and it represents the motorbike and... | from sagemaker.predictor import json_serializer , json_deserializer , RealTimePredictorfrom sagemaker.content_types import CONTENT_TYPE_CSV , CONTENT_TYPE_JSON % % timess_predict = sagemaker.RealTimePredictor ( endpoint=ss_model.endpoint_name , sagemaker_session=sess , content_type = 'image/jpeg ' , accept = 'image/png... | How to retrieve the labels used in a segmentation mask in AWS Sagemaker |
Python | How come this code does not throw an error when run by the Python interpreter . Output is [ ' A ' , ' B ' , ' C ' , 'D ' , ' E ' ] . I thought Python would give me an error on the second statement since a has only 3 elements . Does this feature have any natural uses while coding ? | a = [ ' A ' , ' B ' , ' C ' ] a [ 20 : ] = [ 'D ' , ' E ' ] print a | Curious behaviour of Python lists |
Python | I am learning about methods like argwhere and nonzero in NumPy . It appears that thenumpy.nonzero ( x ) the function returns a tuple of one-dimensional ndarray objects so that the output of this function could be used for indexing.I have not ready the C source code of nonzero because I do n't know how to find it . Howe... | import numpy as npfrom numpy.random import Generator , PCG64rg = Generator ( PCG64 ( ) ) x = rg.integers ( 0,2 , ( 10000,10000 ) ) y = np.nonzero ( x ) print ( y [ 0 ] .base is y [ 1 ] .base ) z = y [ 0 ] .baseprint ( type ( z ) , z.shape ) print ( np.array_equal ( z [ : ,0 ] .reshape ( -1 ) , y [ 0 ] ) ) print ( np.ar... | Inefficiency of Numpy Argwhere |
Python | I made a typo in my code that went completely silent syntactically.If you have n't noticed it , it 's the use of : instead of = when declaring the variable dict_args.So my question is , does the python syntax : a:1 , by itself , hold any meaning ? Or should it hypothetically be considered a syntax error ? | dict_args : { `` arg1 '' :1 , '' arg2 '' :2 , '' arg3 '' :3 } # ... . Some more codesome_function ( **dict_args ) # ... . Some more code | Should n't `` a:1 '' be a syntax error in python ? |
Python | I am fairly new to python and I 'm writing a secure ftp server/client to handle basic uploading/downloading of files ( but encrypted ) .To ensure the client has the secret key , I encrypt and send a randomized 32 byte number . The client must decrypt the number , add one , re-encrypt it , and return it to the server . ... | if int.from_bytes ( challenge , `` big '' ) + 1 == int.from_bytes ( response , `` big '' ) : print ( `` Good\nExpected : { 0 } \nReceived : { 0 } '' .format ( int.from_bytes ( challenge , `` big '' ) + 1 , int.from_bytes ( response , `` big '' ) ) ) else : print ( `` Bad\nExpected : { 0 } \nReceived : { 0 } '' .format ... | Python inconsistent error when comparing two very large numbers |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.