lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I want to create 2 new columns which would give me the closest value and ID to a certain value . This is how my df in python is structured : Essentially , I want to create a new column ( called 'closest_time ' & 'closest_price ' ) which would be the closest p_price to the x_price for that group only ( hence the group b... | x_time expiration x_price p_time p_price 100 4 55.321 100 21 105 4 51.120 105 25 110 4 44.412 110 33.1 100 5 9.1 100 3.1 105 5 9.5 105 5.1 110 5 8.2 110 12.1 100 6 122.1 100 155.9 105 6 144.1 105 134.2 ... ... . x_time expiration x_price p_time p_price closest_price closest_p_time 100 4 55.321 100 21 33.1 110 105 4 51.... | Finding closest value while grouping by a column |
Python | A discussion with a friend led to the following realization : The second example is clearly more efficient simply by reducing the number of instructions.My question is , is there a name for this optimization , and why does n't it happen in the first example ? Also , I 'm not sure if this is a duplicate of Why does n't ... | > > > import dis > > > i = lambda n : n*24*60*60 > > > dis.dis ( i ) 1 0 LOAD_FAST 0 ( n ) 3 LOAD_CONST 1 ( 24 ) 6 BINARY_MULTIPLY 7 LOAD_CONST 2 ( 60 ) 10 BINARY_MULTIPLY 11 LOAD_CONST 2 ( 60 ) 14 BINARY_MULTIPLY 15 RETURN_VALUE > > > k = lambda n : 24*60*60*n > > > dis.dis ( k ) 1 0 LOAD_CONST 4 ( 86400 ) 3 LOAD_FAST... | Optimization of arithmetic expressions - what is this technique called ? |
Python | Suppose I have 2 matrices M and N ( both have > 1 columns ) . I also have an index matrix I with 2 columns -- 1 for M and one for N. The indices for N are unique , but the indices for M may appear more than once . The operation I would like to perform is , Is there a more efficient way to do this other than a for loop ... | for i , j in w : M [ i ] += N [ j ] | numpy : efficiently summing with index arrays |
Python | My laptop has 4 cores , and after some simple testing , I found my CPU usage is at 100 % when I 'm using multiprocessing with 4 jobs or more , about 75 % with 3 jobs , about 50 % with 2 jobs and 25 % with 1 job . This makes perfect sense to me.Then I found that my program runs my jobs 4 times faster with multiprocessin... | import multiprocessingimport timedef worker ( num ) : print ( `` Worker '' +str ( num ) + '' start ! '' ) for i in range ( 30000000 ) : abc = 123 print ( `` Worker '' +str ( num ) + '' finished ! '' ) returnif __name__ == '__main__ ' : jobs = [ ] start = time.time ( ) for i in range ( 5 ) : p = multiprocessing.Process ... | Multiprocessing speed up vs number of cores |
Python | I just read another users question while looking for a way to compute the differences in two lists.Python , compute list differenceMy question is why would I dorather than doingedit : just noticed the second diff function actually returned the similarities . It should be correct now . | def diff ( a , b ) : b = set ( b ) return [ aa for aa in a if aa not in b ] def diff ( a , b ) : tmp = [ ] for i in a : if ( i not in b ) : tmp.append ( i ) return tmp | Why use a set for list comparisons ? |
Python | What 's going on belowWhy does the iteration stop at 8 without any error ? Reproducible on both python2.7 and python 3.5 . | > > > d = { 0:0 } > > > for i in d : ... del d [ i ] ... d [ i+1 ] = 0 ... print ( i ) ... 01234567 > > > | Modifying a dict during iteration |
Python | simple model ( models.py ) : simple factory ( test_factories.py ) : In manage.py shell : current date is 2017-08-16 and fake date is 1999-09-09 . Inside freeze_time , date.today ( ) give fake date but factoryboy is not affected by freezegun . It still give real current date.Is this bug ? If yes , bug with factoryboy or... | from django.db import modelsclass MyModel ( models.Model ) : start_date = models.DateField ( ) from datetime import dateimport factoryfrom .models import MyModelclass MyModelFactory ( factory.django.DjangoModelFactory ) : class Meta : model = MyModel start_date = date.today ( ) In [ 1 ] : from datetime import dateIn [ ... | factoryboy not working with freezegun |
Python | Today I 'm requesting help with a Python script that I 'm writing ; I 'm using the CSV module to parse a large document with about 1,100 rows , and from each row it 's pulling a Case_ID , a unique number that no other row has . For example : As you can see , this list is quite an eyeful , so I 'd like to include a smal... | [ '10215 ' , '10216 ' , '10277 ' , '10278 ' , '10279 ' , '10280 ' , '10281 ' , '10282 ' , '10292 ' , '10293 ' , '10295 ' , '10296 ' , '10297 ' , '10298 ' , '10299 ' , '10300 ' , '10301 ' , '10302 ' , '10303 ' , '10304 ' , '10305 ' , '10306 ' , '10307 ' , '10308 ' , '10309 ' , '10310 ' , '10311 ' , '10312 ' , '10313 ' ,... | Collapse sequences of numbers into ranges |
Python | I have a problem I think should be easy but ca n't find solution , I want to find the matching values in two arrays , then use the indices of one of these to find values in another arrayClearly the above method does work , but it 's very slow , and this is just an example , in the work I 'm actually do a , b1 , b2 are ... | import numpy as npa=np.random.randint ( 0,200,100 ) # rand int arrayb1=np.random.randint ( 0,100,50 ) b2=b1**3c= [ ] for i in range ( len ( a ) ) : for j in range ( len ( b1 ) ) : if b1 [ j ] ==a [ i ] : c.append ( b2 [ j ] ) c=np.asarray ( c ) | Return values from array based on indices of common values in two other arrays |
Python | So I have these two df 's : df A : df B : What I would like to do is add a third column to df A based on the correspondence of df B regarding TYPE : I tried this code : But I think I am making more mistakes . Hopefully somebody can help me . Thanks in advance . | ID TYPE 1 A2 B3 C4 A5 C TYPE MEASUREA 0.3B 0.4C 0.5 ID TYPE MEASURE1 A 0.32 B 0.43 C 0.54 A 0.35 C 0.5 def operation ( row ) : RESULT=B.loc [ titlevar [ 'TYPE ' ] == row [ 'TYPE ' ] ] [ [ 'MEASURE ' ] ] .values return RESULTA [ 'MEASURE ' ] = A.apply ( lambda row : operation ( row ) , axis=1 ) | Pandas dataframe create a new column based on columns of other dataframes |
Python | I 'm writing some integration tests that involve a Python application running under uwsgi.To test an aspect of this , I am running an uwsgi spooler , which requires that the master process is running.If pytest has a failed test , it returns a non-zero exit code , which is great.Without the master process , the entire u... | FROM python:3.6.4-slim-stretchWORKDIR /srvRUN apt-get update \ & & apt-get install -y build-essential \ & & pip install uwsgi pytestCOPY test_app.py /srv/CMD [ '/bin/bash ' ] import pytestdef test_this ( ) : assert 1==0 $ docker build -t=test . $ docker run test uwsgi -- chdir /srv -- pyrun /usr/local/bin/pytest ... ==... | How to get uwsgi to exit with return code of any failed sub-process |
Python | I have been trying to wrap my head around why this is happening but am hoping someone can shed some light on this . I am trying to tag the following text : using the following code : and am getting the following result : And I do n't get it . Does anyone know what is the reason for this inconsistency ? I am not very pa... | ae0.475 X mod ae0.842 X modae0.842 X mod ae0.775 X mod import nltkfile = open ( `` test '' , `` r '' ) for line in file : words = line.strip ( ) .split ( ' ' ) words = [ word.strip ( ) for word in words if word ! = `` ] tags = nltk.pos_tag ( words ) pos = [ tags [ x ] [ 1 ] for x in range ( len ( tags ) ) ] key = ' '.j... | Is POS tagging deterministic ? |
Python | Say I create python lists in two ways.In the first case I use simple assignment : In the second case I use append ( ) method on list : But I get unexpected ( for me ) output : What happens internally with Python memory management ? Why do the 'same ' lists have different sizes ? | my_list = [ ] print ( my_list , '- > ' , my_list.__sizeof__ ( ) ) my_list = [ 1 ] print ( my_list , '- > ' , my_list.__sizeof__ ( ) ) my_list = [ 1 , 1 ] print ( my_list , '- > ' , my_list.__sizeof__ ( ) ) my_list = [ ] print ( my_list , '- > ' , my_list.__sizeof__ ( ) ) my_list.append ( 1 ) print ( my_list , '- > ' , ... | Why do lists with the same data have different sizes ? |
Python | I have a grid of circular data , e.g . the data is given by its angle from 0 to π . Within this data , I have another smaller grid.This might look like this : What I want to do is to interpolate the black data on the red dots . Therefore I 'm using scipy.interpolate.griddata . This will give me the following result : A... | import numpy as npfrom matplotlib import pyplot as pltfrom scipy.interpolate import griddataax = plt.subplot ( ) ax.set_aspect ( 1 ) # Simulate some given data.x , y = np.meshgrid ( np.linspace ( -10 , 10 , 20 ) , np.linspace ( -10 , 10 , 20 ) ) phi = np.arctan2 ( y , x ) % ( 2 * np.pi ) data = np.arctan2 ( np.cos ( ph... | Python : How to unwrap circular data to remove discontinuities ? |
Python | I have noticed that attempting to speed up numpy code that involves generating large numbers of random numbers by vectorising the python for loops out can have the opposite result and can slow it down . The output of the following bit of code is : took time 0.588 and took time 0.789 . This goes against my intuition for... | import timeimport numpy as npN = 50000M = 1000repeats = 10start = time.time ( ) for i in range ( repeats ) : for j in range ( M ) : r = np.random.randint ( 0 , N , size=N ) print 'took time ' , ( time.time ( ) -start ) /repeatsstart = time.time ( ) for i in range ( repeats ) : r = np.random.randint ( 0 , N , size= ( N ... | Numpy random number generation runs slower after being vectorised |
Python | We are migrating from one content system into another and have tons of HTML where there are lines , for example , like this : I am looking for a way to strip HTML with Python where there is no text output to the screen . So a line similar to this would be stripped.And , this is just one of MANY examples of lines where ... | < p style= '' text-align : justify ; '' > < i > < /i > < /p > | Removing empty nodes from HTML |
Python | I am trying to come up with a way to generate all possible unique strings from an alphabet of 20 characters where the order within the string does n't matter , and the length of the string can vary . So , for instance , for a string of length 3 , the possible strings would be AAA , AAB , AAC , etc. , but would not incl... | alphabet = [ `` A '' , '' C '' , '' D '' , '' E '' , '' F '' , '' G '' , '' H '' , '' I '' , '' K '' , '' L '' , `` M '' , '' N '' , '' P '' , '' Q '' , '' R '' , '' S '' , '' T '' , '' V '' , '' W '' , '' Y '' ] combos = [ ] for a in range ( len ( alphabet ) ) : for b in range ( a , len ( alphabet ) ) : for c in range... | Variable number of predictable for loops in Python |
Python | I am working on Python 2.7 and I am trying to overload __getitem__ and __setitem__ from a class that inherits list . Let 's say I have this class A : With square brackets , A.__getitem__ or A.__setitem__ should be called . Normally it is like that , but when I use [ : ] the parent implementation is called instead . Why... | class A ( list ) : def __getitem__ ( self , key ) : print `` GET ! '' def __setitem__ ( self , key , value ) : print `` SET ! '' a = A ( [ 1 ] ) a [ 1 ] # prints GET ! a [ `` 1 '' ] # prints GET ! a [ : : ] # prints GET ! a [ slice ( None ) ] # prints GET ! a [ : ] # returns the list [ 1 ] a [ 1 ] = 2 # prints SET ! a ... | Why are my subclass 's __getitem__ and __setitem__ not called when I use [ : ] ? |
Python | I have array and need max of rolling difference with dynamic window.So first I create difference by itself : Then replace upper triangle matrix to 0 : Last need max values per diagonal , so it means : So expected output is : What is some nice vectorized solution ? Or is possible some another way for expected output ? | a = np.array ( [ 8 , 18 , 5,15,12 ] ) print ( a ) [ 8 18 5 15 12 ] b = a - a [ : , None ] print ( b ) [ [ 0 10 -3 7 4 ] [ -10 0 -13 -3 -6 ] [ 3 13 0 10 7 ] [ -7 3 -10 0 -3 ] [ -4 6 -7 3 0 ] ] c = np.tril ( b ) print ( c ) [ [ 0 0 0 0 0 ] [ -10 0 0 0 0 ] [ 3 13 0 0 0 ] [ -7 3 -10 0 0 ] [ -4 6 -7 3 0 ] ] max ( [ 0,0,0,0,... | Max value per diagonal in 2d array |
Python | I am trying to learn python language and it 's concept . I wrote some code to play with multithreading . But i notice that there is no execution time difference between multi and single threading.The machine which is to run script has 4 core/thread . Each file 's size in the Raw Data is bigger than 25 mb . So i think m... | def get_tokens ( file_name , map ) : print ( file_name ) counter = 0 with open ( file_name , ' r ' , encoding='utf-8-sig ' ) as f : for line in f : item = json.loads ( line , encoding='utf-8 ' ) if 'spot ' in item and item [ 'sid ' ] == 4663 : counter+=1 if counter == 500 : break tokens = nltk.word_tokenize ( item [ 's... | Why is there no execution time difference between multithreading and singlethreading |
Python | Apologize if this has been asked before , somehow I am not able to find the answer to this.Let 's say I have two lists of values : that represents indexes of rows and columns respectively . The two lists combined signified sort of coordinates in the matrix , i.e ( 0,0 ) , ( 1,2 ) , ( 2,3 ) .I would like to use those co... | rows = [ 0,1,2 ] cols = [ 0,2,3 ] data = np.ones ( ( 4,4 ) ) data [ rows , cols ] = np.nanarray ( [ [ nan , 1. , 1. , 1 . ] , [ 1. , 1. , nan , 1 . ] , [ 1. , 1. , 1. , nan ] , [ 1. , 1. , 1. , 1 . ] ] ) df = pd.DataFrame ( np.ones ( ( 4,4 ) ) ) for _r , _c in zip ( rows , cols ) : df.iat [ _r , _c ] = np.nan | How to change dataframe cells values with `` coordinate-like '' indexes stored in two lists/vectors/series ? |
Python | Can I call a method to process data by combining strings ? For example , it is OK to type data.image.truecolor ( ) in code ? My problem is : if I have a data object named data ( not a string ) , how to combine `` .image.truecolor '' sting to call method to process the data ? It is like : Of course , it is failed . I go... | data.image.truecolor ( ) # This line is successful to call method result=getattr ( data , '' .image.truecolor '' ) result ( ) # which is equivalent to the code above data.image.fog ( ) data.image.ir108 ( ) data.image.dnb ( ) data.image.overview ( ) # ... . and other many methods methods= [ `` fog '' , '' ir108 '' , '' ... | How to call method by string ? |
Python | Currently when I want to define a setter and leave getter alone I do this : Is there any way to make it shorter ? I 'd like to skip this part as it always look the same : | @ propertydef my_property ( self ) : return self._my_property @ my_property.setterdef my_property ( self , value ) : value.do_some_magic ( ) self._my_property = value @ propertydef my_property ( self ) : return self._my_property | Defining setter in a shorter way |
Python | There are three types of foods were provided i.e . meat , cake and pizza and N different stores selling it where , i can only pick one type of food fromeach store . Also I can only buy items in A , B and C numbers where ' A ' means , Meat from total ' A ' number of different stores ( see example ) . My task isto consum... | 10 < = number of stores < br > 5 3 2 < = out of 10 stores I can pick meat from 5 stores only . Similarly , I can pick cake from 3 out of 10 stores ... 56 44 41 1 < = Energy level of meat , cake and pizza - ( 56 , 44 , 41 ) for first store. < br > 56 84 45 240 98 49 391 59 73 469 94 42 581 64 80 655 76 26 763 24 22 881 ... | Maximize consumption Energy |
Python | I want to implement the following algorithm , taken from this book , section 13.6 : I do n't understand how to implement the update rule in pytorch ( the rule for w is quite similar to that of theta ) .As far as I know , torch requires a loss for loss.backwward ( ) .This form does not seem to apply for the quoted algor... | def _update_grads_with_eligibility ( self , is_critic , delta , discount , ep_t ) : gamma = self.args.gamma if is_critic : params = list ( self.critic_nn.parameters ( ) ) lamb = self.critic_lambda eligibilities = self.critic_eligibilities else : params = list ( self.actor_nn.parameters ( ) ) lamb = self.actor_lambda el... | Pytorch : How to create an update rule that does n't come from derivatives ? |
Python | I have one column containing all the data which looks something like this ( values that need to be separated have a mark like ( c ) ) : And I want it split into two columns looking like this : Question 2 : What if the countries did not have a pattern like ( c ) ? | UK ( c ) LondonWalesLiverpoolUS ( c ) ChicagoNew YorkSan FranciscoSeattleAustralia ( c ) SydneyPerth London UKWales UKLiverpool UKChicago USNew York USSan Francisco USSeattle USSydney AustraliaPerth Australia | How do I create a new column in a dataframe from an existing column using conditions ? |
Python | Many regex engines match . * twice in a single-line string , e.g. , when performing regex-based string replacement : The 1st match is - by definition - the entire ( single-line ) string , as expected.In many engines there is a 2nd match , namely the empty string ; that is , even though the 1st match has consumed the en... | # .NET , via PowerShell ( behavior also applies to the -replace operator ) PS > [ regex ] : :Replace ( ' a ' , ' . * ' , ' [ $ & ] ' [ a ] [ ] # ! ! Note the *2* matches , first the whole string , then the empty string # Node.js $ node -pe `` ' a'.replace ( / . */g , ' [ $ & ] ' ) '' [ a ] [ ] # Ruby $ ruby -e `` puts ... | Why do some regex engines match . * twice in a single input string ? |
Python | I have a python module that defines a number of classes : From within the module , how might I add an attribute that gives me all of the classes ? dir ( ) gives me the names of everything from within my module , but I ca n't seem to figure out how to go from the name of a class to the class itself from within the modul... | class A ( object ) : def __call__ ( self ) : print `` ran a '' class B ( object ) : def __call__ ( self ) : print `` ran b '' class C ( object ) : def __call__ ( self ) : print `` ran c '' | How can I dynamically get the set of classes from the current python module ? |
Python | I want to open Windows Explorer and select a specific file.This is the API : explorer /select , '' PATH '' . Therefore resulting in the following code ( using python 2.7 ) : The code works fine , but when I switch to non-shell mode ( with pythonw ) , a black shell window appears for a moment before the explorer is laun... | import osPATH = r '' G : \testing\189.mp3 '' cmd = r'explorer /select , '' % s '' ' % PATHos.system ( cmd ) import subprocess , _subprocessdef launch_without_console ( cmd ) : `` Function launches a process without spawning a window . Returns subprocess.Popen object . '' suinfo = subprocess.STARTUPINFO ( ) suinfo.dwFla... | Launch a GUI process without spawning a black shell window |
Python | I have 2 codes which did the same work as which i am asking , but still i did n't get any useful or better code for my data set to make it useful for me , First let me clear what i am doing .I have 2 TEXT files , one name as input_num and second named as input_data as it is clear from names that input_num.txt have numb... | ASA5.txt DF4E6.txt DFS6Q7.txt > 56|61|83|92|ASA5Dogsarebarking import osimport refile_c = open ( 'num_data.txt ' ) file_c = file_c.read ( ) lines = re.findall ( r'\w+\.txt \d+ ' , file_c ) numbers = { } for line in lines : line_split = line.split ( '.txt ' ) hash_name = line_split [ 0 ] count = line_split [ 1 ] numbers... | Length cutting through file handling |
Python | I have following datasetCode to reproduce : Suppose I have to Change only the maximum value of each group of `` Item '' column by adding 1.the output should be like this : I tried df [ 'New_Count ' ] =df.groupby ( [ 'Item ' ] ) [ 'Count ' ] .transform ( lambda x : max ( x ) +1 ) but all the values in `` Count '' was re... | Item CountA 60A 20A 21B 33B 33B 32 import pandas as pddf = pd.DataFrame ( [ [ ' A ' , 60 ] , [ ' A ' , 20 ] , [ ' A ' , 21 ] , [ ' B ' , 33 ] , [ ' B ' , 33 ] , [ ' B ' , 32 ] , ] , columns= [ 'Item ' , 'Count ' ] ) Item Count New_CountA 60 61A 20 20A 21 21B 33 34B 33 34B 32 32 Item Count New_CountA 60 61A 20 61A 21 61... | How to change only the maximum value of a group in pandas dataframe |
Python | I am trying to get the email provider from the mail column of the Dataframe and create a new column named `` Mail_Provider '' . For example , taking gmail from a @ gmail.com and storing it in `` Mail_Provider '' column . Also I would like to extract Country ISD fro Phone column and Create a new column for that . Is the... | data = pd.DataFrame ( { `` Name '' : [ `` A '' , '' B '' , '' C '' ] , '' mail '' : [ `` a @ gmail.com '' , '' b @ yahoo.com '' , '' c @ gmail.com '' ] , '' Adress '' : [ `` Adress1 '' , '' Adress2 '' , '' Adress3 '' ] , '' Phone '' : [ `` +91-1234567890 '' , '' +88- 0987654321 '' , '' +27-2647589201 '' ] } ) Name mail... | Extracting particular characters/ text from DataFrame column |
Python | I am using Django and I am wondering how I can accomplish this . It works fine in python in Linux but the HTML Templating language keeps saying it can not parse the array.It says it can not parse the remainder and then it displays the list . | { % if myvalue in [ `` 128 '' , '' 256 '' , '' 512 '' , '' 768 '' , '' 1024 '' , '' 1536 '' , '' 2048 '' , '' 3072 '' , '' 5120 '' , '' 10240 '' ] % } < p > Hello World { % endif % } | Python Value in List |
Python | James Powell , in his short description for an upcoming presentation , says he is the proud inventor of one of the gnarliest Python one-liners : I am trying to figure out this generator , and since I live with Python 2.7.x , I 'm also tripping over the ( yield from g ) expression.How do I read this , and what would be ... | ( None for g in g if ( yield from g ) and False ) > > > l = [ 10 , 11 , iter ( xrange ( 5 ) ) , 12 , 13 ] > > > g = iter ( l ) > > > flat_g = ( None for g in g if ( yield from g ) and False ) > > > list ( flat_g ) [ 10 , 11 , 0 , 1 , 2 , 3 , 4 , 12 , 13 ] | Python : understanding ( None for g in g if ( yield from g ) and False ) |
Python | Assuming that the computer running this program has an infinite amount of memory , I 'm interested in where Python will break when running the following : For fun , I implemented hyperoperators in python as the module hyperop . One of my examples is Graham 's number : The condensed version of the class hyperop looks li... | def GrahamsNumber ( ) : # This may take awhile ... g = 4 for n in range ( 1,64+1 ) : g = hyperop ( g+2 ) ( 3,3 ) return g def __init__ ( self , n ) : self.n = n self.lower = hyperop ( n - 1 ) def _repeat ( self , a , b ) : if self.n == 1 : yield a i = 1 while True : yield a if i == b : break i += 1def __call__ ( self ,... | What technical limitations prevent the calculation of Graham 's number in python ? |
Python | Short version : I want to crate function which replace all named groups in regular expression with coresponding data from datadict.For example : But i have no idea how to do it.Some addtional info : I have code which iterate trough list of tuples containing name and pattern and trying to use re.search . In case that re... | Input : expr=r '' / ( ? P < something > \w+ ) /whatever/ ( ? P < something2 > \w+ ) '' data= { `` something '' :123 , `` something2 '' : `` thing '' } Output : `` /123/whatever/thing '' class UrlResolver ( ) : def __init__ ( self ) : self.urls = { } def parse ( self , app , url ) : for pattern in self.urls [ app ] : da... | How to compose string from regex pattern with named groups and datadict in python ? |
Python | In the question What does the `` yield '' keyword do ? , I found a Python syntax being used that I did n't expect to be valid . The question is old and has a huge number of votes , so I 'm surprised nobody at least left a comment about this function definition : What I tried to get this sort of syntax evaluated : assig... | def node._get_child_candidates ( self , distance , min_dist , max_dist ) : if self._leftchild and distance - max_dist < self._median : yield self._leftchild if self._rightchild and distance + max_dist > = self._median : yield self._rightchild | Is it possible to def a function with a dotted name in Python ? |
Python | I have a list of text files file1.txt , file2.txt , file3.txt .. filen.txt that I need to shuffle creating one single big file as result *.Requirements : 1 . The records of a given file need to be reversed before being shuffled 2 . The records of a given file should keep the reversed order in the destination file 3 . I... | File1.txt -- -- -- -- -File1Record1File1Record2File1Record3File1Record4File2.txt -- -- -- -- -File2Record1File2Record2File3.txt -- -- -- -- -File3Record1File3Record2File3Record3File3Record4File3Record5 ResultFile.txt -- -- -- -- -- -- -- File3Record5 -|File2Record2 |File1Record4 |File3Record4 -|File2Record1 |File1Recor... | Shuffle the records of a list of text files in one single file |
Python | Certain list comprehensions do n't work properly when I embed IPython 0.10 as per the instructions . What 's going on with my global namespace ? | $ python > > > import IPython.Shell > > > IPython.Shell.IPShellEmbed ( ) ( ) In [ 1 ] : def bar ( ) : pass ... : In [ 2 ] : list ( bar ( ) for i in range ( 10 ) ) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -NameError Traceback ( most recent call last )... | How do I embed IPython with working generator expressions ? |
Python | Is there a simple and direct way to add 'one ' at float number in Python ? I mean this : This is not what I want , because it gives me 0.0144000000001 . | if a == 0.0143 : a = plus ( a ) assert a == 0.0144def plus ( a ) : sa = str ( a ) index = sa.find ( ' . ' ) if index < 0 : return a+1 else : sb = ' 0'*len ( sa ) sb [ index ] = ' . ' sb [ -1 ] = 1 return a+float ( sb ) | How to plus one at the tail to a float number in Python ? |
Python | I was messing around with a small custom data object that needs to be hashable , comparable , and fast , when I ran into an odd-looking set of timing results . Some of the comparisons ( and the hashing method ) for this object simply delegate to an attribute , so I was using something like : However upon testing , I di... | def __hash__ ( self ) : return self.foo.__hash__ ( ) Python 3.3.4 ( v3.3.4:7ff62415e426 , Feb 10 2014 , 18:13:51 ) [ MSC v.1600 64 bit ( AMD64 ) ] on win32Type `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > import timeit > > > > > > sugar_setup = `` '\ ... import datetime ... ... | Why are explicit calls to magic methods slower than `` sugared '' syntax ? |
Python | I solved a problem on Project Euler but it took about 4 minutes to run , which is above the recommended time , so I was looking through the different solutions in the forum . One of them included the symbol < < in a list comprehension . This is what it looked likeI ca n't find anywhere what exactly this < < symbol does... | blist.extend ( [ ( i < < 1 ) + 3 for i in range ( num ) if alist.get ( i ) ] ) | What does < < do in Python ? |
Python | Perhaps not such a big deal , but it breaks my heart to follow this : deltas = data [ 1 : ] - data [ : -1 ] with this : For this particular example ... is there a better way to do the cleansing part ? Question part two : What if the cleansing rules are more complicated , or less complicated than this example . For exam... | for i in range ( len ( deltas ) ) : if deltas [ i ] < 0 : deltas [ i ] = 0 if deltas [ i ] > 100 : deltas [ i ] = 0 | Can I cleanse a numpy array without a loop ? |
Python | I have difficult time understanding how the shape of resultant array be determined after slicing in numpy . For example I am using the following simple code : Output of this is : In both of these cases , content is same ( as it should be ) . But they differ in shapes . So , how does the resultant shape is determined by... | import numpy as nparray=np.arange ( 27 ) .reshape ( 3,3,3 ) slice1 = array [ : ,1:2,1 ] slice2= array [ : ,1,1 ] print `` Content in slice1 is `` , slice1print `` Shape of slice1 is `` , slice1.shapeprint `` Content in slice2 is `` , slice2print `` Shape of Slice2 is '' , slice2.shape Content in slice1 is [ [ 4 ] [ 13 ... | Determining the shape of result array after slicing in Numpy |
Python | Is the following syntax not supported by f-strings in Python 3.6 ? If I line join my f-string , the substitution does not occur : returns : If I remove the line-join : it works as expected : In PEP 498 , backslashes within an f-string are expressly not supported : Escape sequences Backslashes may not appear inside the ... | SUB_MSG = `` This is the original message . `` MAIN_MSG = f '' This longer message is intended to contain `` \ `` the sub-message here : { SUB_MSG } '' print ( MAIN_MSG ) This longer message is intended to contain the sub-message here : { SUB_MSG } SUB_MSG = `` This is the original message . `` MAIN_MSG = f '' This lon... | Is line-joining unsupported by f-strings ? |
Python | I have several decorators on each function , is there a way to pack them in to one instead ? change to : | @ fun1 @ fun2 @ fun3def do_stuf ( ) : pass @ all_funs # runs fun1 fun2 and fun3 , how should all_funs look like ? def do_stuf ( ) : pass | How can I pack several decorators into one ? |
Python | When I easy_install some python modules , warnings such as : sometimes get emitted . Where ( what package / source file ) do these messages come from ? Why is referencing __file__ or __path__ considered a bad thing ? | < some module > : module references __file__ < some module > : module references __path__ < some module > : module MAY be using inspect.trace < some module > : module MAY be using inspect.getsourcefile | warnings emitted during 'easy_install ' |
Python | From a numeric age pandas column , discretize as ageD with qcut , we create open bounds from the qcut bounds : From Index ( [ u ' [ 5 , 30 ] ' , u ' ( 30 , 70 ] ' ] , dtype='object ' ) we make bopens : Then we convert categorical variable into dummy/indicator variables with get_dummies : I want to enrich the data frame... | import pandas as pdfrom itertools import chaind = { 'age ' : { 0 : 5 , 1 : 23 , 2 : 43 , 3 : 70 , 4 : 30 } } df = pd.DataFrame.from_dict ( d ) df [ 'ageD ' ] = pd.qcut ( df.iloc [ : , 0 ] , 2 ) df.ageD.cat.categories # Index ( [ u ' [ 5 , 30 ] ' , u ' ( 30 , 70 ] ' ] , dtype='object ' ) > > > bopens = get_open_bounds (... | Create open bounds indicators from pandas get_dummies on discretized numerical |
Python | Say I have one list , And another , ( You can imagine that the second list was created with an itertools.groupby on an animal being a house pet . ) Now say I want to give the first list the same sublist structure as the second.I might do something like this : Which I have n't totally debugged but I think should work . ... | list1 = [ 'Dog ' , 'Cat ' , 'Monkey ' , 'Parakeet ' , 'Zebra ' ] list2 = [ [ True , True ] , [ False ] , [ True ] , [ False ] ] list3 = [ [ 'Dog ' , 'Cat ' ] , [ 'Monkey ' ] , [ 'Parakeet ' ] , [ 'Zebra ' ] ] list3 = [ ] lengths = [ len ( x ) for x in list2 ] count = 0for leng in lengths : templist = [ ] for i in range... | Copying sublist structure to another list of equal length in Python |
Python | Consider the following arrangement of letters : Start at the top letter and choose one of the two letters below , Plinko-style , until you reach the bottom . No matter what path you choose you create a four-letter word : BOND , BONE , BORE , BORN , BARE , BARN , BAIN , or BAIT . The fact that DENT reads across the bott... | B O A N R I D E N T | How to build a Plinko board of words from a dictionary better than brute force ? |
Python | I am trying to calculate all the distances between approximately a hundred thousand points . I have the following code written in Fortran and compiled using f2py : I am compiling the fortran code using the following python code setup_collision.py : Then running it as follows : Using this code with 30,000 atoms , what s... | C 1 2 3 4 5 6 7C123456789012345678901234567890123456789012345678901234567890123456789012 subroutine distances ( coor , dist , n ) double precision coor ( n,3 ) , dist ( n , n ) integer n double precision x1 , y1 , z1 , x2 , y2 , z2 , diff2cf2py intent ( in ) : : coor , distcf2py intent ( in , out ) : : distcf2py intent... | Why is my Fortran code wrapped with f2py using so much memory ? |
Python | I am setting up the following example which is similar to my situation and data : Say , I have the following DataFrame : Now , I have the following function , which returns the discount amount based on the following logic : Now I want the resulting DataFrame : So I decided to call series.map on the column price because... | df = pd.DataFrame ( { 'ID ' : [ 1,2,3,4 ] , 'price ' : [ 25,30,34,40 ] , 'Category ' : [ 'small ' , 'medium ' , 'medium ' , 'small ' ] } ) Category ID price0 small 1 251 medium 2 302 medium 3 343 small 4 40 def mapper ( price , category ) : if category == 'small ' : discount = 0.1 * price else : discount = 0.2 * price ... | Setting value to a copy of a slice of a DataFrame |
Python | I have a script where I 'm loading a file which takes a while because there is quite much data to read and to prevent the user from terminating the process I want to show some kind of loading indication . I thought this was a good opportunity to learn how to use the multiprocessing module so I wrote this example to tes... | import time , multiprocessingdef progress ( ) : delay = 0.5 while True : print `` Loading . `` , time.sleep ( delay ) print `` \b . `` , time.sleep ( delay ) print `` \b . `` , time.sleep ( delay ) print `` \r \r '' , returndef loader ( filename , con ) : # Dummy loader time.sleep ( 5 ) con.send ( filename ) con.close ... | Only one process prints in unix , multiprocessing python |
Python | I was working on a Flask project , getting some data from an API wrapper . The wrapper returned a generator object , so I print the values ( for obj in gen_object : print obj ) before passing it to Flask 's render_template ( ) . When requesting the page while printing the objects , the page is empty . But removing the ... | @ app.route ( '/ ' ) def front_page ( ) : top_stories = r.get_front_page ( limit=10 ) # this for loop prevents the template from rendering the stories for s in top_stories : print s return render_template ( 'template.html ' , stories=top_stories ) | Do Python generator objects become `` unusable '' after being traversed ? |
Python | I have been absolutely racking my brain over this , and ca n't seem to work out how to get around the issue . Please note that I have cut alot of irrelevant fields out of my modelsI am in the middle of coding up my SQL-Alchemy models , and have encountered the following issue : Due to multiple billing systems , each wi... | class Subscription ( Base ) : id = db.Column ( db.Integer , primary_key=True ) name = db.Column ( db.String ( 255 ) ) secret = db.Column ( postgresql.BYTEA ) type = db.Column ( SubscriptionType.db_type ( ) ) status = db.Column ( StatusType.db_type ( ) ) subscription_id = db.Column ( db.Integer ) __tablename__ = 'subscr... | Inheritance + Foreign Keys |
Python | I have a series of input files such as : in my code I am trying to capture 2 elements from each line , the first is the number after where it says exon , the second is the gene ( the number and letter combo surrounded by `` '' , e.g . `` KDM4A '' . Here is my code : for some reason start works fine but genes is not cap... | chr1 hg19_refFlat exon 44160380 44160565 0.000000 + . gene_id `` KDM4A '' ; transcript_id `` KDM4A '' ; chr1 hg19_refFlat exon 19563636 19563732 0.000000 - . gene_id `` EMC1 '' ; transcript_id `` EMC1 '' ; chr1 hg19_refFlat exon 52870219 52870551 0.000000 + . gene_id `` PRPF38A '' ; transcript_id `` PRPF38A '' ; chr1 h... | splitting lines with `` from an infile in python |
Python | I 'm trying to perform basic affine transformation using pivot points.On both images I made 3 points ( R , G & B ) and saved them in separate images ( 'earth_keys.png ' for 'earth.png ' and 'earth2_keys.png ' for 'earth2.png ' ) . All I want is to match pivot points on 'earth2.png ' with pivot points on 'earth.png'.Sti... | import cv2import numpy as npimport PILimport matplotlib.pyplot as pltimg = cv2.imread ( 'earth.png ' ) img_pivots = cv2.imread ( 'earth_keys.png ' ) map_img = cv2.imread ( 'earth2.png ' ) map_pivots = cv2.imread ( 'earth2_keys.png ' ) pts_img_R = np.transpose ( np.where ( img_pivots [ : , : , 2 ] > 0 ) ) pts_img_G = np... | OpenCV affine transformation wo n't perform |
Python | Just a quick silly question . How do I write a trailing slash in a raw string literal ? | r = r'abc\ ' # syntax errorr = r'abc\\ ' # two slashes : `` abc\\ '' | Trailing slash in a raw string |
Python | I 'm trying to install a package with setuptools including console_scripts on Windows 7 . I 'm trying to change the value of my PYTHONUSERBASE to install into a custom directory with the -- user flag . If I use backslashes in the value of PYTHONUSERBASE , as ineverything works fine . However , if I use a forward slash ... | set PYTHONUSERBASE=C : \testing set PYTHONUSERBASE=C : /testing | -- setup.py| -- foobar\| -- -- __init__.py| -- -- __main__.py def main ( ) : print ( 'This is the main function ' ) from setuptools import setupsetup ( name='foobar ' , version= ' 1.0.0 ' , packages= [ 'foobar ' ] , entry_points= { 'console_scripts ' : [... | Python setuptools is stripping slashes from path arguments on Windows |
Python | I have a generative adversarial networks , where the discriminator gets minimized with the MSE and the generator should get maximized . Because both are opponents who pursue the opposite goal.What do I have to adapt , to get a generator model which profits from a high MSE value ? | generator = Sequential ( ) generator.add ( Dense ( units=50 , activation='sigmoid ' , input_shape= ( 15 , ) ) ) generator.add ( Dense ( units=1 , activation='sigmoid ' ) ) generator.compile ( loss='mse ' , optimizer='adam ' ) generator.train_on_batch ( x_data , y_data ) | Maximize the MSE of a keras model |
Python | I 've been perusing some of the source code for numpy and I noticed that a lot of the c source code uses the construction @ variablename @ . For example , in the file `` npy_math_complex.c.src '' ( located here ) : What do @ ctype @ and @ c @ mean ? Are these some sort of macros ? I 'm guessing they are n't normal C-ma... | /*==========================================================* Constants*=========================================================*/static const @ ctype @ c_1 @ c @ = { 1.0 @ C @ , 0.0 } ; static const @ ctype @ c_half @ c @ = { 0.5 @ C @ , 0.0 } ; static const @ ctype @ c_i @ c @ = { 0.0 , 1.0 @ C @ } ; static const @ ... | How is the at sign ( @ ) used in the c source code for numpy ? |
Python | I have a pandas dataframe with 2 columns . Some of the MessageID 's end on the same row that they start with the NewMessageID like in index row 0 below . But others like index row 2 doesnt end until index row 4 . I am looking for a clever way to simplify the output in a new dataframe.I am looking for an output like : | df MessageID NewMessageID0 28 101 21 92 4 183 3 64 18 225 99 1026 102 1187 1 20 df1 Start Finish0 28 10 1 21 92 4 223 3 64 99 1185 1 20 | Pandas How to create a new dataframe with a start and end even if on different rows |
Python | EditThe accepted answer works for sets that satisfy the requirements of a strict partially ordered set , so that a directed acyclic graph can be constructed : irreflexivity not a < a : the list does not contain items like [ ' a ' , ' a ' ] transitivity if a < b and b < c then a < c : the list does not contain items lik... | def get_order ( _list ) : order = _list [ 0 ] for sublist in _list [ 1 : ] : if not sublist : continue if len ( sublist ) == 1 : if sublist [ 0 ] not in order : order.append ( sublist [ 0 ] ) continue new_order = order.copy ( ) for index , value in enumerate ( sublist ) : inserted = False new_order_index = None if valu... | Logically sorting a list of lists ( partially ordered set - > topological sort ) |
Python | Let 's say I have a Python 3 source file in cp1251 encoding with the following content : If I run the file , I 'll get this : SyntaxError : Non-UTF-8 code starting with '\xfd ' in file ... on line 1 but no encoding declared ; see http : //python.org/dev/peps/pep-0263/ for detailsThat 's clear and expected - I understan... | # эюяьъ ( some Russian comment ) print ( 'Hehehey ' ) # coding : utf-8 # эюяьъ ( some Russian comment ) print ( 'Hehehey ' ) 23 20 fd fe ff fa fc ... 23 20 63 6f 64 69 6e 67 3a 20 75 74 66 2d 38 0a23 20 fd fe ff fa fc ... # coding : utf-8 # эюяъь ( some Russian comment ) print ( 'Hehehey ' ) print ( 'эюяъь ' ) | How does the Python compiler preprocess the source file with the declared encoding ? |
Python | Hi I 'm trying to write a module that lets me read and send data via pyserial . I have to be able to read the data in parallel to my main script . With the help of a stackoverflow user , I have a basic and working skeleton of the program , but when I tried adding a class I created that uses pyserial ( handles finding p... | File `` < ipython-input-1-830fa23bc600 > '' , line 1 , in < module > runfile ( ' C : ... /pythonInterface1/Main.py ' , wdir= ' C : /Users/Daniel.000/Desktop/Daniel/Python/pythonInterface1 ' ) File `` C : ... \Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py '' , line 827 , in runfile execfile ( f... | pyserial with multiprocessing gives me a ctype error |
Python | We can initialise a new dict instance from a list of keys : And a querydict is a dict , so this should work , right ? Of course I can do something lame like QueryDict ( 'spam & spam & potato ' ) , but my question : is the .fromkeys method usable at all , or completely broken ? If the former , how do you use it ? If the... | > > > dict.fromkeys ( [ 'spam ' , 'spam ' , 'potato ' ] ) { 'potato ' : None , 'spam ' : None } > > > QueryDict.fromkeys ( [ 'spam ' , 'spam ' , 'potato ' ] ) TypeError : __init__ ( ) takes at least 2 arguments ( 1 given ) | Initialising a QueryDict.fromkeys |
Python | I want to compare two pandas dataframes and find out the rows that are only in df1 , by comparing the values in column A and B. I feel like I could somehow perform this by using merge but can not figure out..df1df2Dataframe I want to see | import pandas as pddf1 = pd.DataFrame ( [ [ 1,11 , 111 ] , [ 2,22 , 222 ] , [ 3 , 33 , 333 ] ] , columns= [ ' A ' , ' B ' , ' C ' ] ) df2 = pd.DataFrame ( [ [ 1 , 11 ] ] , columns= [ ' A ' , ' B ' ] ) A B C0 1 11 1111 2 22 2222 3 33 333 A B0 1 11 A B C1 2 22 2222 3 33 333 | Eliminate pandas dataframe rows with partial matches |
Python | I am interfacing a C library with python . I have arrays in numpy that I pass to the library using the ctypes attribute of the array.At some point I need to provide an array to the C library , that is expected to be the transposed of the numpy array a I have . ( Another way of putting it is that the C library does not ... | import ctypesimport numpy as npa = np.zeros ( ( 2 , 3 ) ) a.ctypes.strides_as ( ctypes.c_longlong ) [ : ] # returns [ 24 , 8 ] a.T.ctypes.strides_as ( ctypes.c_longlong ) [ : ] # return [ 8 , 24 ] a.T + np.zeros ( a.T.shape ) a.T + np.zeros_like ( a.T ) | Enforcing in-memory transposition of a numpy array |
Python | Using default arguments of the form x= { } usually does not accomplish the intended purpose in Python , since default arguments are bound when a function is defined , not called.The convention seems to be to set mutable objects as default arguments with x=None and then check x is None to assign the proper default when ... | def f ( x=None ) : x = dict ( x ) if x is not None else { } def f ( x= ( ) ) : x = dict ( x ) | What is the most Pythonic way to use an empty dictionary as a default argument ? |
Python | That looks like : I manage to filter on : stores_grouped.filter ( lambda x : ( len ( x ) == 1 ) ) But when I want to filter on two conditions : That my group has length one and id column is equals 10.Any idea ho do so ? | data = { 'year ' : [ '11:23:19 ' , '11:23:19 ' , '11:24:19 ' , '11:25:19 ' , '11:25:19 ' , '11:23:19 ' , '11:23:19 ' , '11:23:19 ' , '11:23:19 ' , '11:23:19 ' ] , 'store_number ' : [ '1944 ' , '1945 ' , '1946 ' , '1948 ' , '1948 ' , '1949 ' , '1947 ' , '1948 ' , '1949 ' , '1947 ' ] , 'retailer_name ' : [ 'Walmart ' , '... | filtering dataframe on multiple conditions |
Python | I have a lower triangular array , like B : I want to flip it to look like : That is , I want to take all the positive values , and reverse within the positive values , leaving the trailing zeros in place . This is not what fliplr does : Any tips ? Also , the actual array I am working with would be something like B.shap... | B = np.array ( [ [ 1,0,0,0 ] , [ .25 , .75,0,0 ] , [ .1 , .2 , .7,0 ] , [ .2 , .3 , .4 , .1 ] ] ) > > > Barray ( [ [ 1. , 0. , 0. , 0 . ] , [ 0.25 , 0.75 , 0. , 0 . ] , [ 0.1 , 0.2 , 0.7 , 0 . ] , [ 0.2 , 0.3 , 0.4 , 0.1 ] ] ) array ( [ [ 1. , 0. , 0. , 0 . ] , [ 0.75 , 0.25 , 0. , 0 . ] , [ 0.7 , 0.2 , 0.1 , 0 . ] , [... | Flip non-zero values along each row of a lower triangular numpy array |
Python | I have a dataframe of categories and amounts . Categories can be nested into sub categories an infinite levels using a colon separated string . I wish to sort it by descending amount . But in hierarchical type fashion like shown.How I need it sortedEDIT : The data frame : Note : this is the order I want it . It may be ... | CATEGORY AMOUNTTransport 5000Transport : Car 4900Transport : Train 100Household 1100Household : Utilities 600Household : Utilities : Water 400Household : Utilities : Electric 200Household : Cleaning 100Household : Cleaning : Bathroom 75Household : Cleaning : Kitchen 25Household : Rent 400Living 250Living : Other 150Liv... | Pandas hierarchical sort |
Python | Consider the following minimal example : Running this code with Python 2 raises exception bar , running it with Python 3 raises exception foo . Yet , the documentation for both Python 2 and Python 3 states that raise with no expression will raise `` the last exception that was active in the current scope '' . Why is th... | try : raise Exception ( 'foo ' ) except Exception : try : raise Exception ( 'bar ' ) except Exception : pass raise | Scope for `` raise '' without arguments in nested exception handlers in Python 2 and 3 |
Python | Just as an example , if I created a new environment.Very obviously , in this case , there are only two top-level dependencies that are added in this environment : python and Jupiter . I know that we can export the dependencies according to Sharing an environmentBut see how verbose it is.Is there a way to only export th... | conda install pythonconda create -- name foo_environmentconda activate foo_environmentconda install pythonconda install jupyterconda env export > environment.yml conda env export > environment.yml name : foo_environmentchannels : - defaults - conda-forgedependencies : - appnope=0.1.0=py37_0 - attrs=19.1.0=py37_1 - back... | Show top level dependencies for a conda managed environment |
Python | I have the following dataframe : How can I drop the row second value after False all the the True values till the second True Value till the second False ? Such as for example : Edit 1 : I would like to add 1 more condition on the new df : As you have mentioned in the comment : [ True , True , True , False , True ] In ... | True_False cum_valDate 2018-01-02 False NaN2018-01-03 False 0.0063992018-01-04 False 0.0104272018-01-05 False 0.0174612018-01-08 False 0.0191242018-01-09 False 0.0204262018-01-10 False 0.0193142018-01-11 False 0.0263482018-01-12 False 0.0330982018-01-16 False 0.0295732018-01-17 False 0.0389882018-01-18 False 0.03737220... | How to conditionally drop rows in pandas |
Python | I have this simple query written in Django and I want to run my tests with pytest.When I run my tests with Django 's test runner : python manage.py test , I get the expected result : But when I do it with pytest -s , I get : Why is n't pytest converting dates like Django 's test runner ? | results = ( self.base_query .order_by ( 'service_date ' ) .extra ( { 'sd ' : `` date ( service_date ) '' } ) .values ( 'sd ' ) .annotate ( created_count=Sum ( 'pax_number ' ) ) ) print 'RESULTS : ' , results RESULTS : < QuerySet [ { 'created_count ' : 14 , 'sd ' : datetime.date ( 2017 , 2 , 24 ) } ] > RESULTS : < Query... | pytest wo n't convert date field to datetime.date object in Django |
Python | Are there good ( suitable for using in real projects ) ways or reducing boilerplate in things like thisI want it to look more like this : or ( more realistically ) Is it possible in Python 2.6+ without overt hacks ? @ link super ( ) in Python 2.x without args | class B ( A ) : def qqq ( self ) : # 1 unwanted token `` self '' super ( B , self ) .qqq ( ) # 7 unwanted tokens plus 2 duplications ( `` B '' , `` qqq '' ) do_something ( ) class B ( A ) : def qqq : super do_something ( ) class B ( A ) : @ autosuper_before def qqq ( self ) : do_something ( ) | How to avoid boilerplate when using super ( ... ) in Python 2.6+ ? |
Python | I was doing one of the course exercises on codeacademy for python and I had a few questions I could n't seem to find an answer to : For this block of code , how exactly does python check whether something is `` in '' or `` not in '' a list ? Does it run through each item in the list to check or does it use a quicker pr... | numbers = [ 1 , 1 , 2 , 3 , 5 , 8 , 13 ] def remove_duplicates ( list ) : new_list = [ ] for i in list : if i not in new_list : new_list.append ( i ) return new_listremove_duplicates ( numbers ) numbers = [ 1 , 1 , 2 , 3 , 5 , 8 , 13 ] def remove_duplicates ( list ) : new_list = [ ] new_list.append ( i for i in list if... | How exactly does Python check through a list ? |
Python | People mentioned in answers a1 , a2 that Due to the way the Python C-level APIs developed , a lot of built-in functions and methods do n't actually have names for their arguments.I found it really annoying cause I 'm not be able to know it by looking at the doc . For instance , eval eval ( expression , globals=None , l... | print ( eval ( ' a+b ' , globals= { ' a':1 , ' b':2 } ) ) | Is there a complete list of built-in functions that can not be called with keyword argument ? |
Python | I 'm looking for a way to have a collection of homogeneous objects , wrap them in another object , but have the wrapper object have the same API as the original and forward the corresponding API call to its object members.Some possible solutions that have been considered , but are inadequate : Rewriting the whole API W... | class OriginalApi : def __init__ ( self ) : self.a = 1 self.b = `` bee '' def do_something ( self , new_a , new_b , put_them_together=None ) : self.a = new_a or self.a self.b = new_b or self.b if put_them_together is not None : self.b = `` { } { } '' .format ( self.a , self.b ) # etc.class WrappedApi : def __init__ ( s... | Wrapping homogeneous Python objects |
Python | So i am reading ( and displaying with a tkinter textbox ) data from a serial connection , but i ca n't process the returning data as i would like to , in order to run my tests . In more simple terms , even though the machine response = 0x1 is displayed , i ca n't read it from the global serBuffer.Before displaying it t... | import tkinter as tkimport serialfrom serial import *serialPort = `` COM3 '' baudRate = 115200ser = Serial ( serialPort , baudRate , timeout=0 , writeTimeout=0 ) # ensure non-blocking # make a TkInter WindowmainWindow = tk.Tk ( ) mainWindow.wm_title ( `` Reading Serial '' ) mainWindow.geometry ( '1650x1000+500+100 ' ) ... | Issue processing data read from serial port , when displaying it in a Tkinter textbox |
Python | I have a DataFrame like this : How can I create a new column which enumerates groups of foo per group of [ 'name ' , 'visit ' ] , like this ? | name visit foo0 andrew BL a1 andrew BL a2 andrew BL b3 andrew BL b4 bob BL c5 bob BL c6 bob BL d7 bob BL d8 bob M12 e9 bob M12 e10 bob M12 f11 bob M12 g12 carol BL h13 carol BL i14 carol BL j15 carol BL k name visit foo enum0 andrew BL a 11 andrew BL a 12 andrew BL b 23 andrew BL b 24 bob BL c 15 bob BL c 16 bob BL d 2... | How to enumerate groups within groups in pandas |
Python | I have a list of lists and I 'd like to get the top x lists with the highest values so top 3 max ( list_of_lists ) would return or if I 'm looping through list_of_lists I could append each of the lists with the top x max values to another list of lists , based upon the index of the selected lists.Here 's the code I 'm ... | list_of_lists = [ [ ' a',1,19,5 ] [ ' b',2,4,6 ] , [ ' c',22,5,9 ] , [ 'd',12,19,20 ] ] [ [ ' c',22 , 5,9 ] , [ 'd',12,19,20 ] , [ ' a',1,19,5 ] ] for y in case_list : last_indices = [ x [ 3 ] for x in case_list ] print ( `` max of cases is : `` , max ( last_indices ) ) max of cases is : 22max of cases is : 22max of ca... | How to find the lists with max values in a list of lists ( where nested lists contain strings and numbers ) ? |
Python | I can not explain the following behaviour : It seems to be that l1 [ : ] [ 0 ] refers to a copy , whereas l1 [ : ] refers to the object itself . | l1 = [ 1 , 2 , 3 , 4 ] l1 [ : ] [ 0 ] = 888print ( l1 ) # [ 1 , 2 , 3 , 4 ] l1 [ : ] = [ 9 , 8 , 7 , 6 ] print ( l1 ) # [ 9 , 8 , 7 , 6 ] | Python : lists and copy of them |
Python | I am scraping a page with BeautifulSoup , and part of the logic is that sometimes part of the contents of a < td > tag can have a < br > in it . So sometimes it looks like this : and sometimes it looks like this : I am looping through this and adding to an output_row list that I eventually add to a list of lists . Whet... | < td class= '' xyz '' > text 1 < br > text 2 < /td > < td class= '' xyz '' > text 1 < /td > elif td.string == None : if 'ABC ' in td.contents [ 2 ] : new_string = td.contents [ 0 ] + ' ' + td.contents [ 2 ] output_row.append ( new_string ) print ( new_string ) else : # this is for another situation and it works fine wi... | Python to CSV is splitting string into two columns when I want one |
Python | This is the code that I have written . As you can see , it has a button which when clicked opens up a Text where one can enter something . It works , the window resizes if you click the button.But I have noticed that , if I maximize and minimize the window just after starting the program ( i.e . the first thing I do is... | from tkinter import *def Home ( ) : global homeP homeP = Tk ( ) homeP.title ( 'Grades ' ) enterButton = Button ( homeP , text='Enter Grades ' , bg='blue ' , fg='white ' , command=enterG ) enterButton.grid ( row=1 , column=0 , padx= ( 5,5 ) , pady= ( 5,2 ) , sticky= '' e '' ) homeP.mainloop ( ) curFrame = `` def enterG ... | Tkinter - Maximizing and minimizing the window before using any widgets , hides the widgets when I use them |
Python | I have the following code in Matlab which I 'm not familiar with : I wrote this following function in Python : I get an error : data is a pandas DataFrame that was read from a CSV file containing triaxial accelerometer data . The axes of the accelerometer data are x , y , and z . The columns for the data frame are time... | function segments = segmentEnergy ( data , th ) mag = sqrt ( sum ( data ( : , 1:3 ) .^ 2 , 2 ) ) ; mag = mag - mean ( mag ) ; above = find ( mag > =th*std ( mag ) ) ; indicator = zeros ( size ( mag ) ) ; indicator ( above ) = 1 ; plot ( mag ) ; hold on ; plot ( indicator*1000 , ' r ' ) end def segment_energy ( data , t... | How do I convert matrices from Matlab to Python ? |
Python | So I 'm teaching myself Python , and I 'm having an issue with lists . I want to pass my function a list and pop items off it while retaining the original list . How do I make python `` instance '' the passed list rather that passing a pointer to the original one ? Example : Output : [ 0 , 1 , 2 ] [ 5 , 4 , 3 ] Desired... | def burninate ( b ) : c = [ ] for i in range ( 3 ) : c.append ( b.pop ( ) ) return ca = range ( 6 ) d = burninate ( a ) print a , d | Passing a list while retaining the original |
Python | I was reading through the answers earning a `` reversal '' badge and I found a question regarding recursion where the OP did n't bother to do much of their homework assignment up front . Aside from some really funny answers , @ machielo posted an answer in python that I had to run on my machine to get a grip on . I 'm ... | def recursive ( x ) : if x > 10 : print recursive ( x/10 ) return x % 10 > > > recursive ( 2678 ) 2678 > > > 2678/10267 > > > 267/1026 > > > 26/102 > > > 2 % 102 > > > def recursive ( x ) : if x > 10 : print x print recursive ( x/10 ) return x % 10 > > > # I will comment the interpreter session here ... > > > recursive... | I Do n't Understand This Use of Recursion |
Python | How come this code runs for me ? I thought slots worked as a restriction . I 'm running Python 2.6.6 . | class Foo ( ) : __slots__ = [ ] def __init__ ( self ) : self.should_not_work = `` or does it ? '' print `` This code does not run , '' , self.should_not_workFoo ( ) | I do n't know how to make __slots__ work |
Python | I am installing airflow via command : python3 setup.py install . It takes in the requirements file , requirements/athena.txt which is : apache-airflow [ celery , postgres , hive , password , crypto ] ==1.10.1I got an error : To remove this error , I set export SLUGIFY_USES_TEXT_UNIDECODE=yes and export AIRFLOW_GPL_UNID... | RuntimeError : By default one of Airflow 's dependencies installs a GPL dependency ( unidecode ) . To avoid this dependency set SLUGIFY_USES_TEXT_UNIDECODE=yes in your environment when you install or upgrade Airflow . To force installing the GPL version set AIRFLOW_GPL_UNIDECODE ➜ athena-py git : ( pyspark-DataFrameSta... | Unable to install Airflow even after setting SLUGIFY_USES_TEXT_UNIDECODE and AIRFLOW_GPL_UNIDECODE |
Python | I run yield from generator and yield from list many times . List version gives always better performance , while my intuition tells me rather opposite conclusions - making list requires i.e . memory allocation at startup . Why we can notice such performance differences ? | Python 3.6.8 ( default , Oct 7 2019 , 12:59:55 ) Type 'copyright ' , 'credits ' or 'license ' for more informationIPython 7.9.0 -- An enhanced Interactive Python . Type ' ? ' for help.In [ 1 ] : def yield_from_generator ( ) : ... : yield from ( i for i in range ( 10000 ) ) ... : In [ 2 ] : def yield_from_list ( ) : ...... | ` yield from ` generator vs ` yield from ` list performance |
Python | According to this test : There is no difference between .decode ( ) and unicode ( ) : Am I right ? If so , why do we have two different ways of accomplishing the same thing ? Which one should I use ? Is there any subtle difference ? | # -*- coding : utf-8 -*-ENCODING = 'utf-8 ' # what is the difference between decode and unicode ? test_cases = [ 'aaaaa ' , 'ááááá ' , 'ℕℤℚℝℂ ' , ] FORMAT = ' % -10s % 5d % -10s % -10s % 5d % -10s % 10s'for text in test_cases : decoded = text.decode ( ENCODING ) unicoded = unicode ( text , ENCODING ) equal = decoded ==... | Difference between decode and unicode ? |
Python | I 'm running this SVD solver from scipy with the below code : I expected the printed mean value to be the same each time , however it changes and seems to cycle through a few favourite values . I 'm happy to accept that behaviour as a consequence of the low level optimisation/random seeding.What I do n't quite get is w... | import numpy as npfrom scipy.sparse.linalg import svdsfeatures = np.arange ( 9 , dtype=np.float64 ) .reshape ( ( 3,3 ) ) for i in range ( 10 ) : _ , _ , V = svds ( features,2 ) print i , np.mean ( V ) | scipy linalg deterministic/non-deterministic code |
Python | I 've been reading some of the code in a standard threading library ( Python 2.6 ) and there was a piece of code which made me wonder . It can be shorten to the following structure ( compare to __bootstrap_inner method in threading.py ) : These variables do not go outside of foo scope . Is there any reason to delete th... | def foo ( ) : exc_type , exc_value , exc_tb = sys.exc_info ( ) try : # some code except : # some code finally : del exc_type , exc_value , exc_tb | Deleting variables in Python standard libraries |
Python | Considder the following interactive exampleDoes anyone know if there is already an implementation somewhere out there with a version of imap ( and the other itertools functions ) such that the second time list ( l ) is executed you get the same as the first . And I do n't want the regular map because building the entir... | > > > l=imap ( str , xrange ( 1,4 ) ) > > > list ( l ) [ ' 1 ' , ' 2 ' , ' 3 ' ] > > > list ( l ) [ ] class cmap : def __init__ ( self , function , *iterators ) : self._function = function self._iterators = iterators def __iter__ ( self ) : return itertools.imap ( self._function , *self._iterators ) def __len__ ( self ... | Itertools for containers |
Python | Similar questions have been brought ( good speed comparison there ) on this same subject . Hopefully this question is different and updated to Python 2.6 and 3.0.So far I believe the faster and most compatible method ( among different Python versions ) is the plain simple + sign : But I keep hearing and reading it 's n... | text = `` whatever '' + `` you `` + SAY | Speed vs security vs compatibility over methods to do string concatenation in Python |
Python | For example : In the above examples the value_counts works perfectly and give the required result . whereas when coming to larger dataframes it is giving a different output . Here the A values are already sorted and counts are also same , but the order of index that is A changed after value_counts . Why is it doing cor... | df1 = pd.DataFrame ( np.repeat ( np.arange ( 1,7 ) ,3 ) , columns= [ ' A ' ] ) df1.A.value_counts ( sort=False ) 1 32 33 34 35 36 3Name : A , dtype : int64 df2 = pd.DataFrame ( np.repeat ( np.arange ( 1,7 ) ,100 ) , columns= [ ' A ' ] ) df2.A.value_counts ( sort=False ) 1 1002 1003 1004 1005 1006 100Name : A , dtype : ... | Pandas Series value_counts working differently for different counts |
Python | I am trying to get a conceptual understanding of the nature of Python functions and methods . I get that functions are actually objects , with a method that is called when the function is executed . But is that function-object method actually another function ? For example : If I look at dir ( fred ) , I see it has an ... | def fred ( ) : pass | Which is more fundamental : Python functions or Python object-methods ? |
Python | I have a set of bitstrings : { '0011 ' , '1100 ' , '1110 ' } ( all bitstrings within a set are of same length ) .I want to quickly find the bitstring of same length that has the smallest max-similarity to the set . Max-similarity can be computed as such : I know that I can iterate through all the possible bitstrings of... | def max_similarity ( bitstring , set ) : max = 0 for item in set : temp = 0 for i in range ( len ( bitstring ) ) : if bitstring [ i ] == item [ i ] : temp += 1 if temp > max : max = temp return max def int2bin ( integer , digits ) : if integer > = 0 : return bin ( integer ) [ 2 : ] .zfill ( digits ) else : return bin (... | Search for bitstring most unlike a set of bitstrings |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.