lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | Consider the following image , stored as a numpy array : Zeros represent background pixels , 1,2,3 and 4 represent pixels that belong to objects . You can see that objects always form contiguous islands or regions in the image . I would like to know the distance between every pair of objects . As distance measure I 'd ... | a = [ [ 0,0,0,0,0,1,1,0,0,0 ] , [ 0,0,0,0,1,1,1,1,0,0 ] , [ 0,0,0,0,0,1,1,0,0,0 ] , [ 0,0,0,0,0,0,0,0,0,0 ] , [ 0,0,0,0,0,2,0,0,0,0 ] , [ 0,0,0,0,0,2,2,0,0,0 ] , [ 0,0,0,0,0,2,0,0,0,0 ] , [ 0,0,0,0,3,3,3,0,0,0 ] , [ 4,0,0,0,0,0,0,0,0,0 ] , [ 4,4,0,0,0,0,0,0,0,0 ] , [ 4,4,4,0,0,0,0,0,0,0 ] ] a = np.array ( a ) | Pairwise Distances Between Two `` islands '' / '' connected components '' in Numpy Array |
Python | I 'm getting a very odd error using a basic shortcut method in python . It seems , unless I 'm being very stupid , I get different values for A = A + B , and A += B . Here is my code : This basically just calculates the covariance of a vector autoregression . So for : I get : This is correct I believe ( agrees with Mat... | def variance ( phi , sigma , numberOfIterations ) : variance = sigma for k in range ( 1 , numberOfIterations ) : phik = np.linalg.matrix_power ( phi , k ) variance = variance + phik*sigma*phik.T return variance phi = np.matrix ( ' 0.7 0.2 -0.1 ; 0.001 0.8 0.1 ; 0.001 0.002 0.9 ' ) sigma = np.matrix ( ' 0.07 0.01 0.001 ... | Python numpy addition error |
Python | I recently learned that Python has not only a module named ctypes , which has a docs page , but also a module named _ctypes , which does n't ( but is nonetheless mentioned a few times in the docs ) . Some code on the internet , like the snippet in this Stack Overflow answer , uses this mysterious undocumented _ctypes m... | Python 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 ctypes , _ctypes > > > print ( ctypes.__doc__ ) create and manipulate C data types in Python > > > print ( _ctypes.__doc_... | ctypes vs _ctypes - why does the latter exist ? |
Python | I have a 2-dimensional array of integers , we 'll call it `` A '' . I want to create a 3-dimensional array `` B '' of all 1s and 0s such that : for any fixed ( i , j ) sum ( B [ i , j , : ] ) ==A [ i.j ] , that is , B [ i , j , : ] contains A [ i , j ] 1s in it the 1s are randomly placed in the 3rd dimension . I know h... | B=np.zeros ( ( X , Y , Z ) ) indexoptions=range ( Z ) for i in xrange ( Y ) : for j in xrange ( X ) : replacedindices=np.random.choice ( indexoptions , size=A [ i , j ] , replace=False ) B [ i , j , [ replacedindices ] ] =1 A=np.array ( [ [ 0,1,2,3,4 ] , [ 0,1,2,3,4 ] , [ 0,1,2,3,4 ] , [ 0,1,2,3,4 ] , [ 0,1,2,3,4 ] ] ) | quickly calculate randomized 3D numpy array from 2D numpy array |
Python | I 'm pretty new to Python , and I have written a ( probably very ugly ) script that is supposed to randomly select a subset of sequences from a fastq-file . A fastq-file stores information in blocks of four rows each . The first row in each block starts with the character `` @ '' . The fastq file I use as my input file... | parser = argparse.ArgumentParser ( ) parser.add_argument ( `` infile '' , type = str , help = `` The name of the fastq input file . `` , default = sys.stdin ) parser.add_argument ( `` outputfile '' , type = str , help = `` Name of the output file . `` ) parser.add_argument ( `` -n '' , help= '' Number of sequences to s... | How can I make my Python script faster ? |
Python | Is it possible to declare a number in Python as Neither seem to work of course . How do you emphasize things like these , for clarity in Python ? Is it possible ? | a = 35_000a = 35,000 | Declaring a number in Python . Possible to emphasize thousand ? |
Python | Let 's quote numpy manual : https : //docs.scipy.org/doc/numpy/reference/arrays.indexing.html # advanced-indexingAdvanced indexing is triggered when the selection object , obj , is a non-tuple sequence object , an ndarray ( of data type integer or bool ) , or a tuple with at least one sequence object or ndarray ( of da... | import numpy as nparr = np.array ( [ 0 , 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 , 90 ] ) indexes = np.array ( [ 3 , 6 , 4 ] ) slicedArr = arr [ indexes ] slicedArr *= 5arr array ( [ 0 , 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 , 90 ] ) import numpy as nparr = np.array ( [ 0 , 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 , 90 ] ) ... | Why does operating on what seems to be a copy of data modify the original data ? |
Python | I want to print the contents of a file to the terminal and in the process highlight any words that are found in a list without modifying the original file . Here 's an example of the not-yet-working code : As it is , only the last item in the list , regardless of what it is or how long the list is , will be highlighted... | def highlight_story ( self ) : `` '' '' Print a line from a file and highlight words in a list . '' '' '' the_file = open ( self.filename , ' r ' ) file_contents = the_file.read ( ) for word in highlight_terms : regex = re.compile ( r'\b ' # Word boundary . + word # Each item in the list . + r 's { 0,1 } ' , # One opti... | Finding and substituting a list of words in a file using regex in Python |
Python | And I print a , Also I print a [ 1 ] [ 0 ] What is [ ... ] ? and when I print a [ 1 ] [ 0 ] , print 2 , not [ ... ] ? | a = [ 2 ] a.append ( a ) [ 2 , [ ... ] ] 2 | python garbage collection about list append itself |
Python | I 've the below dictionary ( Geojson ) : What would be the easiest way to make it into as below , by moving certain values to new keys within properties.Any feedback would be helpful.Thanks . | 'properties ' : { 'fill ' : ' # ffffff ' , 'fill-opacity ' : 1 , 'stroke ' : ' # ffffff ' , 'stroke-opacity ' : 1 , 'stroke-width ' : 1.5 , 'title ' : ' 0.00 m ' , 'time ' : '2000-01-31 ' } 'properties ' : { 'style ' : { 'fill ' : ' # ffffff ' , 'fill-opacity ' : 1 , 'stroke ' : ' # ffffff ' , 'stroke-opacity ' : 1 , '... | Shifting values from one key to another key in python dictionary |
Python | I am using the pyo3 rust crate ( version 0.11.1 ) in order to port rust code , into cpython ( version 3.8.2 ) code . I have created a class called my_class and defined the following functions : new , __str__ , and __repr__.TL ; DR : The __str__ function exists on a class ported from rust using the pyo3 crate , but does... | use pyo3 : :prelude : :* ; # [ pyclass ] struct my_class { # [ pyo3 ( get , set ) ] num : i32 , # [ pyo3 ( get , set ) ] debug : bool , } # [ pymethods ] impl my_class { # [ new ] fn new ( num : i32 , debug : bool ) - > Self { my_class { num , debug } } fn __str__ ( & self ) - > PyResult < String > { Ok ( format ! ( ``... | __str__ function of class ported from rust to python using pyo3 does n't get used in print |
Python | I 'm trying to nice print some divisions with Sympy but I noticed it did n't display aligned.Reason/fix for this ? EDIT : I did a lot of reverse-engineering using inspect.getsource and inspect.getsourcefile but it did n't really help out in the end.Pretty Printing in Sympy seems to be relying on the Prettyprinter by Ju... | import sympysympy.init_printing ( use_unicode=True ) sympy.pprint ( sympy.Mul ( -1 , sympy.Pow ( -5 , -1 , evaluate=False ) , evaluate=False ) ) # Output : # -1 # ─── # -5 # Note that `` -5 '' is displayed slightly more on the right than `` -1 '' . import sympyfrom sympy.printing.pretty.stringpict import *sympy.init_pr... | Not aligned Sympy 's nice pritting of division |
Python | Do numpy arrays keep track of their `` view status '' ? What I am looking for is numpy.isview ( ) or something.I want this for code profiling to be sure that I am doing things correctly and getting views when I think I am . | import numpya = numpy.arange ( 100 ) b = a [ 0:10 ] b [ 0 ] = 100print a [ 0 ] # 100 comes out as it is a viewb is a [ 0:10 ] # False ( hmm how to ask ? ) | Can you tell if an array is a view of another ? |
Python | Is there any possible way to achieve a non-lazy left to right invocation of operations on a list in python ? e.g . scalaWhile I realize many folks will not prefer the above syntax , I like the ability to move left to right and add arbitrary operations as we go.The python for comprehension is imo not easy to read when t... | val a = ( ( 1 to 50 ) .map ( _ * 4 ) .filter ( _ < = 170 ) .filter ( _.toString.length == 2 ) .filter ( _ % 20 == 0 ) .zipWithIndex .map { case ( x , n ) = > s '' Result [ $ n ] = $ x '' } .mkString ( `` .. `` ) ) a : String = Result [ 0 ] =20 .. Result [ 1 ] =40 .. Result [ 2 ] =60 .. Result [ 3 ] =80 [ f ( a ) for a ... | Left to right application of operations on a list in python3 |
Python | How exactly does the min function work for lists in python ? For example , gives num2 as the result . Is the comparison value based or length based ? | num = [ 1,2,3,4 , [ 1,2,3 ] ] num2 = [ 1,2,3,4,5 ] min ( num , num2 ) | Comparison on the basis of min function |
Python | I have a nested dictionary whose structure looks like thisEvery key is a string and every value is a dict.I need to replace every empty dict with `` '' . How would I go about this ? | { `` a '' : { } , '' b '' : { `` c '' : { } } } | Replace empty dicts in nested dicts |
Python | I have two lists . The first list is already sorted ( by some other criteria ) such that the earlier in the list , the better.The second list is a list of allowed values : I would like to select the highest sorted value that exists in the allowedList , and I 'm only coming up with silly ways of doing this . Things like... | sortedList = [ '200 ' , '050 ' , '202 ' , '203 ' , '206 ' , '205 ' , '049 ' , '047 ' , '042 ' , '041 ' , '043 ' , '044 ' , '046 ' , '045 ' , '210 ' , '211 ' , '306 ' , '302 ' , '308 ' , '309 ' , '311 ' , '310 ' , '221 ' , '220 ' , '213 ' , '212 ' ] allowedList = [ '001 ' , '002 ' , '003 ' , '004 ' , '005 ' , '006 ' , '... | Finding first instance of one list in a second list |
Python | The code below works but each time you run a program , for example the notepad on target machine , the prompt is stuck until I quit the program.How to run multiple programs at the same time on target machine ? I suppose it can be achieved with either the threads or subprocess modules , but I still can not use the conce... | import socketimport timeimport subprocess # Executar comandos do SO # criando a conexao reversaIP = '192.168.1.33 ' # ip do cliente linux netcat que sera a central de comandoPORT = 443 # usamos a porta de https pra confundir o firewall : a conexao de saida nao sera bloqueadadef connect ( IP , PORT ) : # conectando a ce... | Concurrency with subprocess module . How can I do this ? |
Python | Jump to edit to see more real-life code example , that does n't work after changing the query orderHere are my models : Now , create 2 instances each : If I 'll query for only one model with annotations , I get something like that : This is correct behavior . The problem starts , when I want to get union of those two m... | class ModelA ( models.Model ) : field_1a = models.CharField ( max_length=32 ) field_2a = models.CharField ( max_length=32 ) class ModelB ( models.Model ) : field_1b = models.CharField ( max_length=32 ) field_2b = models.CharField ( max_length=32 ) ModelA.objects.create ( field_1a= '' 1a1 '' , field_2a= '' 1a2 '' ) Mode... | Incorrect results with ` annotate ` + ` values ` + ` union ` in Django |
Python | I 'm trying to figure out the best way to design a couple of classes . I 'm pretty new to Python ( and OOP in general ) and just want to make sure that I 'm doing this right . I have two classes : `` Users '' and `` User '' .If I want to retrieve my users , I use : '' users.users '' seems to be a bit redundant . Am I d... | class User ( object ) : def __init__ ( self ) : passclass Users ( object ) : def __init__ ( self ) : self.users = [ ] def add ( self , user_id , email ) : u = User ( ) u.user_id = user_id u.email = email self.users.append ( u ) users = Users ( ) users.add ( user_id = 1 , email = 'bob @ example.com ' ) for u in users.us... | Python newbie class design question |
Python | I am doing normalization for datasets but the data contains a lot of 0 because of padding.I can mask them during model training but apparently , these zero will be affected when I applied normalization.from sklearn.preprocessing import StandardScaler , MinMaxScalerI am currently using the Sklearn library to do the norm... | [ [ [ 0 0 0 0 0 ] , [ 0 0 0 0 0 ] , [ 0 0 0 0 0 ] ] [ [ 1 2 3 4 5 ] , [ 4 5 6 7 8 ] , [ 9 10 11 12 13 ] ] , [ [ 14 15 16 17 18 ] , [ 0 0 0 0 0 ] , [ 24 25 26 27 28 ] ] , [ [ 0 0 0 0 0 ] , [ 423 2 230 60 70 ] , [ 0 0 0 0 0 ] ] ] scaler = MinMaxScaler ( ) X_train = scaler.fit_transform ( X_train.reshape ( -1 , X_train.sh... | mask 0 values during normalization |
Python | I 've coded for several months in Python , and now i have to switch to Java for work 's related reasons . My question is , there is a way to simulate this kind of statementwithout defining an additional isIn ( ) -like boolean function that scans list_name in order to find var_name ? | if var_name in list_name : # do something | Simulate if-in statement in Java |
Python | I am often tempted not to create a new list when using list comprehensions , because if the list is huge , it would mean more space needed to compute ( the way I understand it the list is not bieng aliased int his case , a new memory space is created for the new list ) As an illustrative example ( this could be done in... | def average_list ( lst ) : lst = [ x for x in lst if x > 0 ] return np.average ( lst ) def average_list ( lst ) : clean_lst = [ x for x in lst if x > 0 ] return np.average ( clean_lst ) | List comprehension and copies of types |
Python | I am trying to switch two elements in the string while keeping all the other characters untouched . Here is an example : Original string : Required output : Notice that element after A* and B* are switched.I was able to compile a RegEx pattern that gives me elements to replace like following : After this stage I need y... | r'xyzA*12*pqR*stB*HS*lmN*opA*45*a4N*gB*SD*drtU*ghy ' r'xyzA*HS*pqR*stB*12*lmN*opA*SD*a4N*gB*45*drtU*ghy ' > > > import re > > > pattern = re.compile ( r ' A\* ( .* ? ) \*.* ? B\* ( .* ? ) \* ' ) > > > M = pattern.findall ( string ) > > > M [ ( '12 ' , 'HS ' ) , ( '45 ' , 'SD ' ) ] | How to switch two elements in string using Python RegEx ? |
Python | I 'm trying to extract the tabular contents available on a graph in a webpage . The content of those tables are only visible when someone hovers his cursor within the area . One such table is this one.Webpage addressThe graph within which the tables are is titled as EPS consensus revisions : last 18 months.I 've tried ... | from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as EClink = `` https : //www.marketscreener.com/SUNCORP-GROUP-LTD-6491453/revisions/ '' driver = webdriver.Chrome ( ) driver.get ( li... | Trouble parsing tabular items from a graph located in a website |
Python | I 'm looking for a way to efficiently get an array of booleans , where given two arrays with equal size a and b , each element is true if the corresponding element of a appears in the corresponding element of b.For example , the following program : Should printKeep in mind this function should be the equivalent ofOnly ... | a = numpy.array ( [ 1 , 2 , 3 , 4 ] ) b = numpy.array ( [ [ 1 , 2 , 13 ] , [ 2 , 8 , 9 ] , [ 5 , 6 ] , [ 7 ] ] ) print ( numpy.magic_function ( a , b ) ) [ True , True , False , False ] [ x in y for x , y in zip ( a , b ) ] | Pythonic and efficient way to do an elementwise `` in '' using numpy |
Python | Google Play ecosystem allows ratings data to be accessible from bucket , i.e . cloud storage.While I can successfully download CSV from Play developer 's console and process it , the file is in utf-16 encoding . Here are the first 180 bytes : or decoded : However , when I try to access ratings via cloud storage : , I r... | '255,254,80,0,97,0,99,0,107,0,97,0,103,0,101,0,32,0,78,0,97,0,109,0,101,0,44,0,65,0,112,0,112,0,32,0,86,0,101,0,114,0,115,0,105,0,111,0,110,0,32,0,67,0,111,0,100,0,101,0,44,0,82,0,101,0,118,0,105,0,101,0,119,0,101,0,114,0,32,0,76,0,97,0,110,0,103,0,117,0,97,0,103,0,101,0,44,0,68,0,101,0,118,0,105,0,99,0,101,0,44,0,82,0... | Can not parse Google Play app ratings data |
Python | I have a list containing thousands of sets similar to this : each set in the list look something like this : I would like to do the set operation : X- ( YUZUAUB ... ... etc ) for every set in the list , for example , this would look something like this : after applying this operation on all elements in set_list the new... | set_list = [ a , b , c , d ] a = set ( [ 1 , 2 , 3 , 4 , 5 ] ) b = set ( [ 4 , 5 , 6 , 7 , 7 , 9 ] ) c = set ( [ 1 , 2 , 6 , 8 , 10 , 12 , 45 ] ) d = set ( [ 11 , 3 , 23 , 3 , 4 , 44 ] ) a = a.difference ( b.union ( c , d ) ) b = b.difference ( c.union ( a , d ) ) c = c.difference ( d.union ( b , a ) ) d = d.difference... | set operation on a list of elements |
Python | I have the following code snippet which i needed to ( massively ) speed up . As is , it 's hugely inefficient.Disassembled : is the outputis a list of tuples in the form ( [ ... ] , number_of_packages ) is the number of packages I need to reach . I can combine as many elements of the list `` input_list '' as I want ( r... | possible_combos.append ( [ comb for comb in itertools.combinations_with_replacement ( input_list , target_number_of_packages ) if np.sum ( [ j [ 1 ] for j in comb ] ) ==target_number_of_packages ] ) possible_combos input_list target_number_of_packages possible_combos.append ( [ comb for comb in itertools.combinations_w... | Can pythons lambda be used to change the inner working of another function ? |
Python | My Django webapp lets users download text files that are generated on the fly : I installed Django Debug Toolbar ( 0.11.0 , since I can not get 1.0.1 to work ) , but when I click to make the download , the toolbar does n't show info about the file that was downloaded , presumably because that is a separate page/request... | response = HttpResponse ( my_file_contents ) response [ 'Content-Disposition ' ] = 'attachment ; filename= '' my file.txt '' 'return response | Django debug toolbar : how do I profile a file download ? |
Python | I am a beginner and just started learning Python couple days ago ( yay ! ) so i 've come across a problem . when i run , this code outputs everything but the text ( txt in file is numbers 0-10 on seperate lines ) | def output ( ) : xf=open ( `` data.txt '' , `` r '' ) print xf print ( `` opened , printing now '' ) for line in xf : print ( xf.read ( ) ) print ( `` and\n '' ) xf.close ( ) print ( `` closed , done printing '' ) | Reading from file |
Python | When trying the following script in Python 2 , its output is and in Python 3 , the script its output is , What may be the reason for that ? | a = 200 print type ( a ) < type 'int ' > a = 200print ( type ( a ) ) < class 'int ' > | Difference of type ( ) function in Python 2 and Python 3 |
Python | I have a a nested list and I 'm trying to get the sum and print the list that has the highest numerical value when the individual numbers are summed togetherI 've been able to print out the results but I think there should be a simple and more Pythonic way of doing this ( Maybe using a list comprehension ) . How would ... | x = [ [ 1,2,3 ] , [ 4,5,6 ] , [ 7,8,9 ] ] highest = list ( ) for i in x : highest.append ( sum ( i ) ) for ind , a in enumerate ( highest ) : if a == max ( highest ) : print ( x [ ind ] ) | What is the proper way to print a nested list with the highest value in Python |
Python | The upshot of the below is that I have an embarrassingly parallel for loop that I am trying to thread . There 's a bit of rigamarole to explain the problem , but despite all the verbosity , I think this should be a rather trivial problem that the multiprocessing module is designed to solve easily . I have a large lengt... | def apply_indexed_fast ( abcissa , func_indices , func_table ) : `` '' '' Returns the output of an array of functions evaluated at a set of input points if the indices of the table storing the required functions are known . Parameters -- -- -- -- -- func_table : array_like Length k array of function objects abcissa : a... | parallelized algorithm for evaluating a 1-d array of functions on a same-length 1d numpy array |
Python | I 'm testing a CreateAPIView with an APITestCase class . Things are working as expected as an anonymous user , but when I login ( ) as a user , I get a 405 HttpResponseNotAllowed exception . I 'm able to successfully create an object while authed as a user through the django-rest-framework web frontend . I 'm using dja... | class SherdNoteCreate ( CreateAPIView ) : serializer_class = SherdNoteSerializer def post ( self , request , *args , **kwargs ) : data = request.data.copy ( ) data [ 'asset ' ] = kwargs.get ( 'asset_id ' ) serializer = SherdNoteSerializer ( data=data ) if serializer.is_valid ( ) : serializer.save ( ) return Response ( ... | 405 error when testing an authed django-rest-framework route |
Python | I 'm appending some weather data ( from json- dict ) - in Japanese to DataFrame.I would like to have something like this But I have thisHow Could I change the Codes to make it like that ? Here is the code | 天気 風 0 状態 : Clouds 風速 : 2.1m 1 NaN 向き : 230 天気 風 0 状態 : Clouds NaN 1 NaN 風速 : 2.1m 2 NaN 向き : 230 df = pd.DataFrame ( columns= [ '天気 ' , ' 風 ' ] ) df = df.append ( { '天気 ' : weather_status } , ignore_index=True ) # 状態 : Clouds - valuedf = df.append ( { ' 風 ' : wind_speed } , ignore_index=True ) # 風速 : 2.1m -valuedf = d... | Add values to existing rows -DataFrame |
Python | I am writing a program which stores some JSON-encoded data in a file , but sometimes the resulting file is blank ( because there was n't found any new data ) . When the program finds data and stores it , I do this : Of course , if the file is blank this will raise an exception , which I can catch but does not let me to... | with open ( 'data.tmp ' ) as f : data = json.load ( f ) os.remove ( 'data.tmp ' ) try : with open ( 'data.tmp ' ) as f : data = json.load ( f ) except : os.remove ( 'data.tmp ' ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > File `` MyScript.py '' , line 50 , in run os.remove ( 'da... | Remove a JSON file if an exception occurs |
Python | I have a 100000000x2 array named `` a '' , with an index in the first column and a related value in the second column . I need to get the median values of the numbers in the second column for each index . This is how I colud do it with a for statement : Obviously it 's too slow with the for iteration : any suggestions ... | import numpy as npb = np.zeros ( 1000000 ) a = np.array ( [ [ 1 , 2 ] , [ 1 , 3 ] , [ 2 , 3 ] , [ 2 , 4 ] , [ 2 , 6 ] , [ 1 , 4 ] , ... ... [ 1000000,6 ] ] ) for i in xrange ( 1000000 ) : b [ i ] =np.median ( a [ np.where ( a [ : ,0 ] ==i ) ,1 ] ) | dealing with arrays : how to avoid a `` for '' statement |
Python | I have an inventory journal that contains products and their relative inventory qty ( resulting_qty ) as well as the loss/gain every time inventory is added or subtracted ( delta_qty ) . The issue is that inventory records do not get updated daily , rather they are only updated when a change in inventory occurs . For t... | | date | timestamp | pid | delta_qty | resulting_qty || -- -- -- -- -- -- | -- -- -- -- -- -- -- -- -- -- -| -- -- -| -- -- -- -- -- -| -- -- -- -- -- -- -- -|| 2017-03-06 | 2017-03-06 12:24:22 | A | 0 | 0.0 || 2017-03-31 | 2017-03-31 02:43:11 | A | 3 | 3.0 || 2017-04-08 | 2017-04-08 22:04:35 | A | -1 | 2.0 || 2017-04-... | Need to expand an inventory journal ( log ) pandas dataframe to include all dates per product id |
Python | I am wondering if python has its error report message equivalent to $ ! in perl ? Anyone who could give me an answer will be greatly appreciated.Added : When Exception occurs , I got something like this . If I apply try and catch block , I can catch it and use sys.exit ( message ) to log the message . But , is there an... | example % ./testFile `` ./test '' , line 7 test1 = test.Test ( dir ) ^SyntaxError : invalid syntax | does python has its error report message like $ ! in perl |
Python | I have a dataframe of shop names that I 'm trying to standardize . Small sample to test here : I set up a regex dictionary to search for a string , and insert a standardized version of the shop name into the column standard . This works fine for this small dataframe : The problem is I have about SIX million rows to sta... | import pandas as pddf = pd.DataFrame ( { 'store ' : pd.Series ( [ 'McDonalds ' , 'Lidls ' , 'Lidl New York 123 ' , 'KFC ' , 'Lidi Berlin ' , 'Wallmart LA 90210 ' , 'Aldi ' , 'London Lidl ' , 'Aldi627 ' , 'mcdonaldsabc123 ' , 'Mcdonald_s ' , 'McDonalds12345 ' , 'McDonalds5555 ' , 'McDonalds888 ' , 'Aldi123 ' , 'KFC-786 ... | How to speed up multiple str.contains searches for millions of rows ? |
Python | What is the best way to copy a table that contains different delimeters , spaces in column names etc . The function pd.read_clipboard ( ) can not manage this task on its own.Example 1 : Expected result : EDIT : Example 2 : Expected result : I look for a universal approach that can be applied to the most common table ty... | | Age Category | A | B | C | D || -- -- -- -- -- -- -- | -- -| -- -- | -- -- | -- -|| 21-26 | 2 | 2 | 4 | 1 || 26-31 | 7 | 11 | 12 | 5 || 31-36 | 3 | 5 | 5 | 2 || 36-41 | 2 | 4 | 1 | 7 || 41-46 | 0 | 1 | 3 | 2 || 46-51 | 0 | 0 | 2 | 3 | Age Category A B C D 21-26 2 2 4 1 26-31 7 11 12 5 31-36 3 5 5 2 36-41 2 4 1 7 41-4... | Parse prettyprinted tabular data with pandas |
Python | I 'm using sklearn pipelines to build a Keras autoencoder model and use gridsearch to find the best hyperparameters . This works fine if I use a Multilayer Perceptron model for classification ; however , in the autoencoder I need the output values to be the same as input . In other words , I am using a StandardScalar i... | from sklearn.datasets import make_classificationfrom sklearn.preprocessing import StandardScalerfrom sklearn.pipeline import Pipelinefrom sklearn.model_selection import GridSearchCV , KFoldfrom keras.models import Sequentialfrom keras.layers import Dense , Dropoutfrom keras.optimizers import RMSprop , Adamfrom tensorfl... | How to scale target values of a Keras autoencoder model using a sklearn pipeline ? |
Python | QuestionHow to shade or colorize the background of a seaborn plot using a column of a dataframe ? Code snippetWhich produced this graph : Desired outputWhat I 'd like to have , according to the value in the new column 'background ' and any palette or user defined colors , something like this : | import numpy as npimport seaborn as sns ; sns.set ( ) import matplotlib.pyplot as pltfmri = sns.load_dataset ( `` fmri '' ) fmri.sort_values ( 'timepoint ' , inplace=True ) ax = sns.lineplot ( x= '' timepoint '' , y= '' signal '' , data=fmri ) arr = np.ones ( len ( fmri ) ) arr [ :300 ] = 0arr [ 600 : ] = 2fmri [ 'back... | Colorize the background of a seaborn plot using a column in dataframe |
Python | It is a little weird to me that the refs number in the interactive environment increases 2 after a new object is defined . I created only one object , is n't it ? | > > > vTraceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > NameError : name ' v ' is not defined [ 41830 refs ] > > > v = `` v '' [ 41832 refs ] | Why does refs increase 2 for every new object in Python ? |
Python | For a given 2D matrix np.array ( [ [ 1,3,1 ] , [ 2,0,5 ] ] ) if one needs to calculate the max of each row in a matrix excluding its own column , with expected example return np.array ( [ [ 3,1,3 ] , [ 5,5,2 ] ] ) , what would be the most efficient way to do so ? Currently I implemented it with a loop to exclude its ow... | n=x.shape [ 0 ] row_max_mat=np.zeros ( ( n , n ) ) rng=np.arange ( n ) for i in rng : row_max_mat [ : ,i ] = np.amax ( s_a_array_sum [ : ,rng ! =i ] , axis=1 ) | What 's a more efficient way to calculate the max of each row in a matrix excluding its own column ? |
Python | Possible Duplicate : Multiprocessing launching too many instances of Python VM I am trying python 2.6 multiprocessing module with this simple code snippet.But this code cause my OS stopped responding . It looks like the CPU is too busy.What 's wrong with my code ? BTW : it seems that multiprocessing module is a bit dan... | from multiprocessing import Poolp = Pool ( 5 ) def f ( x ) : return x*xprint p.map ( f , [ 1,2,3 ] ) | Why python multiprocessing module cause CPU completely run out ? |
Python | I 'm trying to train a multi-layered ANN with pylearn2 , using pre-training with RBM . I 've slightly modified the script called run_deep_trainer that is contained in pylearn2\pylearn2\scripts\tutorials\deep_trainer . I want a 4-layered net , where the first 3 are made with 500 GaussianBinaryRBM and the last one is a m... | from pylearn2.models.rbm import GaussianBinaryRBMfrom pylearn2.models.softmax_regression import SoftmaxRegressionfrom pylearn2.models.mlp import Softmaxfrom pylearn2.training_algorithms.sgd import SGDfrom pylearn2.costs.autoencoder import MeanSquaredReconstructionErrorfrom pylearn2.termination_criteria import EpochCoun... | Pre-training ANN with RBM in pylearn2 |
Python | I recently updated Python 's Numpy package on one of my machines , and apparently I 've been relying on a deprecated feature of numpy for a while now : One of the commenters in the above link pointed out : Probably means you did n't see the deprecation warnings since forever ; ) ... which is correct , I didn't.But why ... | > > > np.__version__ ' 1.10.4 ' > > > a = np.ones ( 10 , dtype=np.uint16 ) > > > a /= 0.5Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > TypeError : ufunc 'true_divide ' output ( typecode 'd ' ) could not be coerced to provided output parameter ( typecode ' H ' ) according to the cas... | Why am I not seeing Numpy 's DeprecationWarning ? |
Python | The public documentation for pandas.io.formats.style.Styler.format says subset : IndexSlice An argument to DataFrame.loc that restricts which elements formatter is applied to.But looking at the code , that 's not quite true ... what is this _non_reducing_slice stuff ? Use case : I want to format a particular row , but ... | if subset is None : row_locs = range ( len ( self.data ) ) col_locs = range ( len ( self.data.columns ) ) else : subset = _non_reducing_slice ( subset ) if len ( subset ) == 1 : subset = subset , self.data.columns sub_df = self.data.loc [ subset ] > > > import pandas as pd > > > > > > df = pd.DataFrame ( [ dict ( a=1 ,... | What does the subset argument do in pandas.io.formats.style.Styler.format ? |
Python | I have measured the positions of different products in different angles positions ( 6 values in steps of 60 deg . over a complete rotation ) . Instead of representing my values on a Cartesian graph where 0 and 360 are the same point , I want to use a polar graph.With matplotlib , I got a spider chart type graph , but I... | # Librariesimport matplotlib.pyplot as pltimport pandas as pdimport numpy as np # Some data to play withdf = pd.DataFrame ( { 'measure ' : [ 10 , -5 , 15,20,20 , 20,15,5,10 ] , 'angle ' : [ 0,45,90,135,180 , 225 , 270 , 315,360 ] } ) # The few lines I would like to avoid ... angles = [ y/180*np.pi for x in [ np.arange ... | Custom Spider chart -- > Display curves instead of lines between point on a polar plot in matplotlib |
Python | In relation to the previous post on stackoverflowModel ( ) got multiple values for argument 'nr_class ' - SpaCy multi-classification model ( BERT integration ) in which my problem partialy have beed resolved I wanted to share the issue which comes up after implementing the solution.if I take out the nr_class argument ,... | ValueError : operands could not be broadcast together with shapes ( 1,2 ) ( 1,5 ) nlp = spacy.load ( 'en_pytt_bertbaseuncased_lg ' ) textcat = nlp.create_pipe ( 'pytt_textcat ' , config= { `` nr_class '' :5 , `` exclusive_classes '' : True , } ) nlp.add_pipe ( textcat , last = True ) textcat.add_label ( `` class1 '' ) ... | SpaCy - ValueError : operands could not be broadcast together with shapes ( 1,2 ) ( 1,5 ) |
Python | You can use function annotations in python 3 to indicate the types of the parameters and return value , like so : But what if you were writing a function that expects a function as a parameter , or returns one ? I realize that you can write any valid expression in for the annotations , so I could write `` function '' a... | def myfunction ( name : str , age : int ) - > str : return name + str ( age ) # usefulfunction | How to indicate that a function expects a function as a parameter , or returns a function , via function annotations ? |
Python | I 'm trying to split a column using regex , but ca n't seem to get the split correctly . I 'm trying to take all the trailing CAPS and move them into a separate column . So I 'm getting all the CAPS that are either 2-4 CAPS in a row . However , it 's only leaving the 'Name ' column while the 'Team ' column is blank.Her... | import pandas as pdurl = `` https : //www.espn.com/nba/stats/player/_/table/offensive/sort/avgAssists/dir/desc '' df = pd.read_html ( url ) [ 0 ] .join ( pd.read_html ( url ) [ 1 ] ) df [ [ 'Name ' , 'Team ' ] ] = df [ 'Name ' ] .str.split ( ' [ A-Z ] { 2,4 } ' , expand=True ) print ( df.head ( 5 ) .to_string ( ) ) RK ... | How can I split columns with regex to move trailing CAPS into a separate column ? |
Python | I am writing a simple program to replace the repeating characters in a string with an * ( asterisk ) . But the thing here is I can print the 1st occurrence of a repeating character in a string , but not the other occurrences . For example , if my input is Google , my output should be Go**le.I am able to replace the cha... | s = 'Google 's = s.lower ( ) for i in s : if s.count ( i ) > 1 : s = s.replace ( i , '* ' ) print ( s ) | Error while Trying To Print the First Occurrence of a repeating Character in a String using Python 3.6 |
Python | I am working on some FASTA-like sequences ( not FASTA , but something I have defined that 's similar for some culled PDB from the PISCES server ) .I have a question . I have a small no of sequences called nCatSeq , for which there are MULTIPLE nBasinSeq . I go through a large PDB file and I want to extract for each nCa... | nCatSeq=item [ 1 ] [ n ] +item [ 1 ] [ n+1 ] +item [ 1 ] [ n+2 ] +item [ 1 ] [ n+3 ] nBasinSeq=item [ 2 ] [ n ] +item [ 2 ] [ n+1 ] +item [ 2 ] [ n+2 ] +item [ 2 ] [ n+3 ] if nCatSeq not in potBasin : potBasin [ nCatSeq ] =nBasinSeqelse : if nBasinSeq not in potBasin [ nCatSeq ] : potBasin [ nCatSeq ] =potBasin [ nCatS... | Nested dictionary |
Python | So I have a df like thisI want to sort it in such an alternating way that within a group , say group `` A '' , the first row should have its highest performing person ( in this case `` Chad Webster '' ) and then in the second row the least performing ( which is `` Sheldon Webb '' ) .The output I am looking for would lo... | In [ 1 ] : data= { 'Group ' : [ ' A ' , ' A ' , ' A ' , ' A ' , ' A ' , ' A ' , ' B ' , ' B ' , ' B ' , ' B ' ] , 'Name ' : [ ' Sheldon Webb ' , ' Traci Dean ' , ' Chad Webster ' , ' Ora Harmon ' , ' Elijah Mendoza ' , ' June Strickland ' , ' Beth Vasquez ' , ' Betty Sutton ' , ' Joel Gill ' , ' Vernon Stone ' ] , 'Per... | How to sort a group in a way that I get the largest number in the first row and smallest in the second and the second largest in the third and so on |
Python | Everywhere I search , they say python dictionary 's does n't have any order.When I run code 1 each time shows a different output ( random order ) . But when I run code 2 it always shows the same sorted output . Why is the dictionary ordered in the second snippet ? Outputscode 1 : code 1 again : code 2 ( always ) : | # code 1 d = { 'one ' : 1 , 'two ' : 2 , 'three ' : 3 , 'four ' : 4 } for a , b in d.items ( ) : print ( a , b ) # code 2 d = { 1 : 10 , 2 : 20 , 3 : 30 , 4 : 40 } for a , b in d.items ( ) : print ( a , b ) four 4two 2three 3one 1 three 3one 1two 2four 4 1 102 203 304 40 | Dictionary order in python |
Python | I have a repeating fringe pattern on my data and I am trying to get it out by Fourier transforming it and deleting the pattern . However I ca n't seem to find the correct way back to image space . taper is just an array that smooths the edges to get rid of the edge effects while doing an FFT . Then I FFT the array and ... | red_cube_array = ( cube_array - np.median ( cube_array ) ) * taperim_fft = ( fftpack.fft2 ( red_cube_array ) ) im_po = fftpack.fftshift ( ( np.conjugate ( im_fft ) * im_fft ) .real ) mask = np.empty_like ( im_po [ 0 ] ) *0 + 1mask [ 417:430 , 410:421 ] = 0mask [ 430:443 , 438:450 ] = 0im_po_mask = im_po * maskim_ifft =... | Fourier filtering , going back to an image |
Python | Is it possible to show the error bars in the legend ? ( Like i draw in red ) They do not necessarily have to be the correct length , it is enough for me if they are indicated and recognizable.My working sample : I tried a few ways , no one works.With Patch in legend_elements i get no lines for the errorbars , with the ... | import pandas as pdimport matplotlib.pyplot as plt test = pd.DataFrame ( data= { 'one':2000 , 'two':300 , 'three':50 , 'four':150 } , index= [ 'MAX ' ] ) fig , ax = plt.subplots ( figsize= ( 5 , 3 ) , dpi=230 ) ax.set_ylim ( -.12 , .03 ) # barplotax = test.loc [ [ 'MAX ' ] , [ 'one ' ] ] .plot ( position=5.5 , color= [... | Errorbar in Legend - Pandas Bar Plot |
Python | Example from PEP 484 -- Type HintsRight way to call the function with strIf I call it with int : Call with listEverything works fine right ? greeting function always accepts str as a parameter.But if I try to test function return type , for example , use the same function but change return type to int.Function returns ... | def greeting ( name : str ) - > str : return 'Hello ' + name > > > greeting ( `` John '' ) 'Hello John ' > > > greeting ( 2 ) TypeError : must be str , not int > > > greeting ( [ `` John '' ] ) TypeError : must be str , not list def greeting ( name : str ) - > int : return 'Hello ' + name > > > greeting ( `` John '' ) ... | Why return type is not checked in python3 ? |
Python | I wrote this rather poor Python function for prime factorization : and it worked as expected , now I was interested in whether the performance could be better when using an iterative approach : But what I observed ( while the functions gave the same results ) was that the iterative function took longer to run . At leas... | import mathdef factor ( n ) : for i in range ( 2 , int ( math.sqrt ( n ) +1 ) ) : if not n % i : return [ i ] + factor ( n//i ) return [ n ] def factor_it ( n ) : r = [ ] i = 2 while i < int ( math.sqrt ( n ) +1 ) : while not n % i : r.append ( i ) n //= i i +=1 if n > 1 : r.append ( n ) return r number = 3112347811412... | Surprised about good recursion performance in python |
Python | I saw some commits in a Python code base removing `` hourglass imports . '' I 've never seen this term before and I ca n't find anything about it via the Python documentation or web search.What are hourglass imports and when would one use or not use them ? My best guess is that removing them makes submodules easier to ... | diff -- git a/tensorflow/contrib/slim/python/slim/nets/vgg.py b/tensorflow/contrib/slim/python/slim/nets/vgg.pyindex 3c29767f2..d4eb43cbb 100644 -- - a/tensorflow/contrib/slim/python/slim/nets/vgg.py+++ b/tensorflow/contrib/slim/python/slim/nets/vgg.py @ @ -37,13 +37,20 @ @ Usage : @ @ vgg_16 @ @ vgg_19 `` '' '' + from... | What are hourglass imports and why would they be avoided in a codebase ? |
Python | When I do : I receive an output of : It 's not only that some of my keys are deleted but also the value it was holding changed . Why is True given priority over another bool keys ? | > > > d= { True : 'yes',1 : 'no',1.0 : 'maybe ' } > > > d > > > { True : 'maybe ' } | Python dictionary breaking the laws of python |
Python | I have a list of tuples I am trying to sort and could use some help . The field I want to sort by in the tuples looks like `` XXX_YYY '' . First , I want to group the XXX values in reverse order , and then , within those groups , I want to place the YYY values in normal sort order . ( NOTE : I am just as happy , actual... | mylist = [ ( u'community_news ' , u'Community : News & Information ' ) , ( u'kf_video ' , u'KF : Video ' ) , ( u'community_video ' , u'Community : Video ' ) , ( u'kf_news ' , u'KF : News & Information ' ) , ( u'kf_magazine ' , u'KF : Magazine ' ) ] sorted = [ ( u'kf_magazine ' , u'KF : Magazine ' ) , ( u'kf_news ' , u'... | Help sorting : first by this , and then by that |
Python | I would like to see the definition of the class list_iterator . When I try to display its definition with the function help I get an error . Is there a module that I have to import in order to access to its help ? More precisely , I would to know how to get a reference to the object iterable that the iterator iterates ... | l = [ 1,2,3,4,5 ] it = iter ( l ) print ( type ( it ) ) # this prints : list_iterator # how to get a reference to l using it import sysl = [ 1,2,3,4 ] print ( sys.getrefcount ( l ) ) # prints 2it = iter ( l ) print ( sys.getrefcount ( l ) ) # prints 3 | Where is the class list_iterator defined ? |
Python | I am trying to understand how static methods work internally . I know how to use @ staticmethod decorator but I will be avoiding its use in this post in order to dive deeper into how static methods work and ask my questions.From what I know about Python , if there is a class A , then calling A.foo ( ) calls foo ( ) wit... | > > > class A : ... x = 'hi ' ... def foo ( ) : ... print ( 'hello , world ' ) ... bar = staticmethod ( foo ) ... > > > A.bar ( ) hello , world > > > A ( ) .bar ( ) hello , world > > > A.bar < function A.foo at 0x00000000005927B8 > > > > A ( ) .bar < function A.foo at 0x00000000005927B8 > > > > A.bar ( 1 ) Traceback ( ... | What magic does staticmethod ( ) do , so that the static method is always called without the instance parameter ? |
Python | Here is what I want to do : Is there a way that I can make the order of elements in a pair irrelevant so when O do the membership testing : Any Idea will be greatly appreciated ! Thanks in Advance ! | m1 = ( a , b ) m2 = ( c , d ) bad_combos = set ( ) bad_combos.add ( ( m1 , m2 ) ) # ( ( a , b ) , ( c , d ) ) ... # adding many other elements in the set # when i do this : if ( m2 , m1 ) in bad_combos : print ( `` Found '' ) else : print ( `` Not Found '' ) # the result is always `` Not Found '' bad_combos.add ( ( m3 ... | Membership testing on set of pairs , how do i make the order of element in pairs irrelevant ? |
Python | We 've made a library which uses massively ( with inheritance ) numpy 's MaskedArrays . But I want to run sphinx 's make doctest without testing the inherited methods from numpy , because they make round about 100 failures.This lookls like this : And now that our library also supports numpy 's functions , therefore we ... | class _frommethod : `` '' '' Adapted from numpy.ma._frommethod `` '' '' def __init__ ( self , func_name ) : self.__name__ = func_name self.__doc__ = getattr ( MaskedArray , func_name ) .__doc__ self.obj = None def __get__ ( self , obj , objtype=None ) : self.obj = obj return self def __call__ ( self , a , *args , **par... | prevent sphinx from executing inherited doctests |
Python | Here are a couple of examples taken from django-basic-apps : What 's the point of this string formatting ? | # self.title is a unicode string alreadydef __unicode__ ( self ) : return u ' % s ' % self.title # ' q ' is a stringsearch_term = ' % s ' % request.GET [ ' q ' ] | ' % s ' % 'somestring ' |
Python | functools.singledispatch helps to define a single-dispatch generic method . Meanwhile , there is super ( ) for calling methods or accessing attributes of a superclass.Is there something like super ( ) that can be used with singledispatch ? I tried the following , but the result of super ( Derived , value ) is just not ... | from functools import singledispatch @ singledispatchdef hello ( value ) : return [ 'default ' ] @ hello.register ( Base ) def hello_base ( value ) : return hello ( super ( Base , value ) ) + [ 'base ' ] @ hello.register ( Derived ) def hello_derived ( value ) : return hello ( super ( Derived , value ) ) + [ 'derived '... | Equivalent to super ( ) for functools.singledispatch |
Python | I have the following two functions : andHowever , when I run both , I find that their results slightly differ : I get : which is very small , but in my case , affects the simulation . If I remove the np.sin from the functions , the difference disappears . Alternatively the difference also goes away if use np.float32 fo... | def loop ( x ) : a = np.zeros ( 10 ) for i1 in range ( 10 ) : for i2 in range ( 10 ) : a [ i1 ] += np.sin ( x [ i2 ] - x [ i1 ] ) return a def vectorized ( x ) : b = np.zeros ( 10 ) for i1 in range ( 10 ) : b += np.sin ( np.roll ( x , i1 ) - x ) return b x = np.arange ( 10 ) a , b = loop ( x ) , vectorized ( x ) print ... | Different result with vectorized code to standard loop in numpy |
Python | I have a first version of legend in the following plot : with the following code : As you can see , I put a title ( k_max = 0.3 and k_max = 1.0 ) for each column of markers and columns.Now , to avoid this redundancy , I am trying to merge all duplicated labels while keeping the title for each marker by doing : This way... | # Plot and save : kmax = 0.3p11 , = plt.plot ( [ 0 ] , marker='None ' , linestyle='None ' , label= ' $ k_ { max } = 0.3 $ ' ) p1 , = plt.plot ( FoM_vs_Density_array_1 [ : ,0 ] , FoM_vs_Density_array_1 [ : ,1 ] , '-b ' , label = ' $ GC_ { sp } $ ' ) p2 , = plt.plot ( FoM_vs_Density_array_1 [ : ,0 ] , FoM_vs_Density_arra... | Matplotlib : How to set a title above each marker which represents a same label |
Python | Many online python examples show interactive python sessions with normal leading `` > > > '' and `` ... '' characters before each line.Often , there 's no way to copy this code without also getting these prefixes.In these cases , if I want to re-paste this code into my own python interpreter after copying , I have to d... | > > > if True : ... print ( `` x '' ) ... | python : ignoring leading `` > > > '' and `` ... '' in interactive mode ? |
Python | How can I cycle through a , b , c by calling change_x ( ) indefinitely ? Output should be : | a = 1b = 2c = 3x = adef change_x ( ) : x = next ? ? print ( `` x : '' , x ) for i in range ( 10 ) : change_x ( ) x : 2x : 3x : 1x : 2 ... | Cycle over list indefinitely |
Python | I 'm trying to parse a logfile of our manufacturing process . Most of the time the process is run automatically but occasionally , the engineer needs to switch into manual mode to make some changes and then switches back to automatic control by the reactor software . When set to manual mode the logfile records the step... | steps = [ 1,2,2 , 'MAN.OP. ' , 'MAN.OP.',2,2,3,3 , 'MAN.OP. ' , 'MAN.OP . ',4,4 ] ser_orig = pd.Series ( steps ) 0 11 22 23 MAN.OP.4 MAN.OP.5 26 27 38 39 MAN.OP.10 MAN.OP.11 412 4dtype : object 0 11 22 23 Manual_Mode_04 Manual_Mode_05 26 27 38 39 Manual_Mode_110 Manual_Mode_111 412 4dtype : object @ step_series.setterd... | Finding contiguous , non-unique slices in Pandas series without iterating |
Python | I tested this : With the following partial output : There are two calls for read syscall with different number of requested bytes.When I repeat the same using dd command , just one read syscall is triggered using the exact number of bytes requested.I have googled this without any possible explanation . Is this related ... | strace python -c `` fp = open ( '/dev/urandom ' , 'rb ' ) ; ans = fp.read ( 65600 ) ; fp.close ( ) '' read ( 3 , `` \211^\250\202P\32\344\262\373\332\241y\226\340\16\16 ! < \354\250\221\261\331\242\304\375\24\36\253 ! \345\311 '' ... , 65536 ) = 65536read ( 3 , `` \7\220-\344\365\245\240\346\241 > Z\330\266^Gy\320\275\... | Why Python splits read function into multiple syscalls ? |
Python | I am solving the analytic intersection of 2 cubic curves , whose parameters are defined in two separate functions in the below code.By plotting the curves , it can be easily seen that there is an intersection : zoomed version : However , the sym.solve is not finding the intersection , i.e . when asking for print 'sol_ ... | import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.font_manager import FontPropertiesimport sympy as symdef H_I ( P ) : return ( -941.254840173 ) + ( 0.014460465765 ) *P + ( -9.41529726451e-05 ) *P**2 + ( 1.23485231253e-06 ) *P**3def H_II ( P ) : return ( -941.254313412 ) + ( 0.014234188877 ) *P + ( -0.00... | Analytic intersection between two cubic expressions |
Python | Long story short ... what happens when all references to a threading.Thread object are lost , such as in this function : It kinda looks like the thread keeps going , but it is behaving oddly and I wondered if there might be odd things happening because the garbage collector improperly deleted it or something.Or do thre... | def myfunc ( ) : def thread_func ( ) : while True : do_useful_things ( ) thethread = threading.Thread ( target = thread_func ) thethread.run ( ) return | What happens when you lose all references to a Python thread ? |
Python | This works but is unwieldy and not very 'Pythonic ' . I 'd also like to be able to run through different values for 'numValues ' , say 4 to 40 ... | innerList = [ ] outerList = [ ] numValues = 12loopIter = 0for i in range ( numValues ) : innerList.append ( 0 ) for i in range ( numValues ) : copyInnerList = innerList.copy ( ) outerList.append ( copyInnerList ) for i in range ( len ( innerList ) ) : for j in range ( loopIter + 1 ) : outerList [ i ] [ j ] = 1 loopIter... | How to create a list of lists where each sub-list 'increments ' as follows : [ 1 , 0 , 0 ] , [ 1 , 1 , 0 ] , [ 1 , 1 , 1 ] |
Python | I have been operating under the theory that generator expressions tend to be more efficient than normal loops . But then I ran into the following example : write a function which given a number , N , and some factors , ps , returns the sum of all the numbers under N that are a multiple of at least one factor.Here is a ... | def loops ( N , ps ) : total_sum = 0 for i in xrange ( N ) : for p in ps : if i % p == 0 : total_sum += i break return total_sumdef genexp ( N , ps ) : return sum ( i for i in xrange ( N ) if any ( i % p == 0 for p in ps ) ) for func in ( 'loops ' , 'genexp ' ) : print func , timeit.timeit ( ' % s ( 100000 , [ 3,5,7 ] ... | Why is this generator expression function slower than the loop version ? |
Python | Consider the following example codeCreating the object within the loop was intended to assure that the destructor of A would be called before the new A object would be created . But apparently the following happens : Initializing object 1Initializing object 2Deleting object 1Deleting object 2Why is the destructor of ob... | class A : def __init__ ( self , i ) : self.i = i print ( `` Initializing object { } '' .format ( self.i ) ) def __del__ ( self ) : print ( `` Deleting object { } '' .format ( self.i ) ) for i in [ 1 , 2 ] : a = A ( i ) | On second initialization of an object , why is __init__ called before __del__ ? |
Python | A user shared with me a link ( shared with just me ... ... ... llama @ bowlcut.com ) . I try to copy the file but I get an error `` File not found '' .If the user changes the share policy to share with everyone & creates a link ( the file number does n't change ) and I rerun it then I am able to copy it . Why are n't I... | def copy_file ( service , origin_file_id , copy_title ) : try : print service.files ( ) .copy ( fileId=origin_file_id , body= { 'title ' : copy_title } ) .execute ( ) except errors.HttpError , error : print 'An error occurred : % s ' % error | Ca n't copy a file shared only with me |
Python | I need to store a large list of numbers in memory . I will then need to check for membership . Arrays are better than lists for memory efficiency . Sets are better than lists for membership checking . I need both ! So my questions are:1 ) How much more memory efficient are arrays than sets ? ( For the converse , see my... | import arrayimport time class TimerContext : def __enter__ ( self ) : self.t0 = time.time ( ) def __exit__ ( self , *args , **kwargs ) : print ( time.time ( ) -self.t0 ) SIZE = 1000000l = list ( [ i for i in range ( SIZE ) ] ) a = array.array ( ' I ' , l ) s = set ( l ) print ( type ( l ) ) print ( type ( a ) ) print (... | Python sets versus arrays |
Python | I am trying to unpack android 11 image / get info from the raw .img for selinux info , symlinks etc.I am using this wonderful tool : https : //github.com/cubinator/ext4/blob/master/ext4.py35.pyand my code looks like this : then I just have to do ./read.py vendor.img and it works.Untill recently I tried this weird vendo... | # ! /usr/bin/env python3import argparseimport sysimport osimport ext4parser = argparse.ArgumentParser ( description='Read < modes , symlinks , contexts and capabilities > from an ext4 image ' ) parser.add_argument ( 'ext4_image ' , help='Path to ext4 image to process ' ) args = parser.parse_args ( ) exists = os.path.is... | python - read file info , permissions from raw ext4 image |
Python | I want to create a 2d numpy array where every element is a tuple of its indices.Example ( 4x5 ) : I would create an python list with the following list comprehension : Is there a faster way to achieve the same , maybe with numpy methods ? | array ( [ [ [ 0 , 0 ] , [ 0 , 1 ] , [ 0 , 2 ] , [ 0 , 3 ] , [ 0 , 4 ] ] , [ [ 1 , 0 ] , [ 1 , 1 ] , [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 4 ] ] , [ [ 2 , 0 ] , [ 2 , 1 ] , [ 2 , 2 ] , [ 2 , 3 ] , [ 2 , 4 ] ] , [ [ 3 , 0 ] , [ 3 , 1 ] , [ 3 , 2 ] , [ 3 , 3 ] , [ 3 , 4 ] ] ] ) [ [ ( y , x ) for x in range ( width ) ] for y in ra... | Create an array where each element stores its indices |
Python | I have a pandas dataframe that I am reading from a defaultdict in Python , but some of the columns have different lengths . Here is what the data might look like : And I am able to pad the blanks with NaNs like so : Which gives : However , what I 'm really looking for is a way to prepend NaNs instead of appending them ... | Date col1 col2 col3 col4 col501-01-15 5 12 1 -15 1001-02-15 7 0 9 11 701-03-15 6 1 2 1801-04-15 9 8 1001-05-15 -4 701-06-15 -11 -101-07-15 6 pd.DataFrame.from_dict ( pred_dict , orient='index ' ) .T Date col1 col2 col3 col4 col501-01-15 5 12 1 -15 1001-02-15 7 0 9 11 701-03-15 NaN 6 1 2 1801-04-15 NaN 9 8 10 NaN01-05-1... | Prepending instead of appending NaNs in pandas using from_dict |
Python | I would appreciate if somebody could help me with this ( and explaining what 's going on ) .This works : But this does not : The behaviour I would like to replicate is : Note that what above also work with mutable objects : Of course , knowing that : I tried ( and failed ) : | > > > from numpy import array > > > a = array ( ( 2 , 1 ) ) > > > b = array ( ( 3 , 3 ) ) > > > l = [ a , b ] > > > a in lTrue > > > c = array ( ( 2 , 1 ) ) > > > c in lTraceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > ValueError : The truth value of an array with more than one element... | Numpy : need a hand in understanding what happens with the `` in '' operator |
Python | Following sample is taken from `` Dive into python '' book.This sample shows documenting the MP3FileInfo , but how can I add help to MP3FileInfo . tagDataMap | class MP3FileInfo ( FileInfo ) : `` store ID3v1.0 MP3 tags '' tagDataMap = ... | Documenting class attribute |
Python | I am working on finding some sort of moving average in a dataframe . The formula will change based on the number of the row it is being computed for . The actual scenario is where I need to compute column Z.Edit-2 : Below is the actual data I am working withThe code snippet I am using is as below : Below is the error I... | Date Open High Low Close0 01-01-2018 1763.95 1763.95 1725.00 1731.351 02-01-2018 1736.20 1745.80 1725.00 1743.202 03-01-2018 1741.10 1780.00 1740.10 1774.603 04-01-2018 1779.95 1808.00 1770.00 1801.354 05-01-2018 1801.10 1820.40 1795.60 1809.955 08-01-2018 1816.00 1827.95 1800.00 1825.006 09-01-2018 1823.00 1835.00 179... | Need to apply different formulas based on the row number in the dataframe |
Python | I want to find a fast way ( without for loop ) in Python to assign reoccuring indices of an array.This is the desired result using a for loop : When I try to add x to a at the indices Px , Py I obviously do not get the same result ( 3.3 vs. 3.1 ) : Is there a way to do this with numpy ? Thanks . | import numpy as npa=np.arange ( 9 , dtype=np.float64 ) .reshape ( ( 3,3 ) ) # The array indices : [ 2,3,4 ] are identical.Px = np.uint64 ( np.array ( [ 0,1,1,1,2 ] ) ) Py = np.uint64 ( np.array ( [ 0,0,0,0,0 ] ) ) # The array to be added at the array indices ( may also contain random numbers ) .x = np.array ( [ .1 , .1... | Assigning identical array indices at once in Python/Numpy |
Python | Let 's say I haveI getWhat I would now like to have are functions between all the orange dots , so something likeThereby , fi should be chosen in a way that it reproduces the shape of the spline fit.I found the post here , but the spline produced there seems incorrect for the example above and it 's also not exactly wh... | import numpy as npfrom scipy.interpolate import UnivariateSpline # `` true '' data ; I do n't know this functionx = np.linspace ( 0 , 100 , 1000 ) d = np.sin ( x * 0.5 ) + 2 + np.cos ( x * 0.1 ) # sample data ; that 's what I actually measuredx_sample = x [ : :20 ] d_sample = d [ : :20 ] # fit splines = UnivariateSplin... | How to convert a spline fit into a piecewise function ? |
Python | I am trying to retrieve the answer for multiplying two int arrays ( output is also an int array ) .For example , num1 = [ 2 , 2 , 0 ] , num2 = [ 1 , 0 ] will give us [ 2 , 2 , 0 , 0 ] What I tried was trying to imitate the grade-school multiplication.However , in the official answer to this question , it adds these two... | def multiply ( num1 , num2 ) : if num1 == [ 0 ] or num2 == [ 0 ] : return [ 0 ] sign = -1 if ( num1 [ 0 ] < 0 ) ^ ( num2 [ 0 ] < 0 ) else 1 num1 [ 0 ] = abs ( num1 [ 0 ] ) num2 [ 0 ] = abs ( num2 [ 0 ] ) res = [ 0 ] * ( len ( num1 ) + len ( num2 ) + 1 ) # space O ( n + m ) for i in range ( len ( num1 ) - 1 , -1 , -1 ) ... | multiplying two int arrays in python |
Python | My dataframe looks like this : Output : A new 'cluster ' occurs after a 0 shows up in the df . I want to give each of these clusters an unique value , like this : I have tried using enumerate and itertools but since I am new to Python I am struggling with the correct usage and syntax of these options . | import pandas as pdexample = [ { ' A':3 } , { ' A':5 } , { ' A':0 } , { ' A':2 } , { ' A':6 } , { ' A':9 } , { ' A':0 } , { ' A':3 } , { ' A':4 } ] df = pd.DataFrame ( example ) print ( df ) df350269034 df3 A5 A0 -2 B6 B9 B0 -3 C4 C | How to assign unique values to groups of rows in a pandas dataframe based on a condition ? |
Python | I am brand new to python frame introspection and I am trying to set a profiler or a tracer in order to keep track of str function calls . I have setup tracers in various ways but think I am missing some key understandings around frame introspection and how to get builtin function names ( ie str ) When I run test_trace ... | def test_trace ( ) : sys.setprofile ( trace_calls ) hi = str ( 'hellllo ' ) stuff = [ ] for i in range ( 10 ) : stuff.append ( str ( random.randrange ( 0 , 10000000000 ) ) ) print ( hi ) os._exit ( 0 ) def trace_calls ( frame , event , arg ) : `` ' if event not in ( 'call ' , 'c_call ' ) : return `` ' stack = collectio... | Python Observing ` str ` calls by through sys.setprofile and frame inspection |
Python | I am trying to make a tic tak toe game with pygame and I was wondering how would I do the logic here is what I have so far . VIDEO < I only have it when I click on the middle button it will display the player 2 x on the screen and then the image that is hovering over my mouse will turn into O for player 1 turn to go BU... | import pygame , randompygame.init ( ) # draw our windowwindow = pygame.display.set_mode ( ( 500,540 ) , pygame.NOFRAME ) pygame.display.set_caption ( `` Tic Tac TOE '' ) MANUAL_CURSOR = pygame.image.load ( 'nw.png ' ) .convert_alpha ( ) MANUAL_CURSOR2 = pygame.image.load ( 'nOW.png ' ) .convert_alpha ( ) bg = pygame.im... | Pygame Tic Tak Toe Logic ? How Would I Do It |
Python | I would like my dice values not to repeat because when it does , it registers a wrong input in my program ( not a crash , simply a string message stating `` Your input was wrong '' ) . It is a board game so I do not want the same values to repeat , for example 6,0 to repeat twice or even thrice . Is there a way to save... | dice = random.randint ( 0,3 ) ans = network.receive ( ) if dice == 0 : guess = str ( random.randint ( 0,4 ) ) + ' , '+str ( random.randint ( 0,4 ) ) elif dice == 1 : guess = str ( random.randint ( 0,4 ) ) + ' , '+str ( random.randint ( 4,9 ) ) elif dice == 2 : guess = str ( random.randint ( 4,9 ) ) + ' , '+str ( random... | Make dice values NOT repeat in if statement |
Python | I was solving this leetcode permutation problem and came across an error that am getting n empty lists inside my returned list which suppose to print different permutations of the given listgetting output = > [ [ ] , [ ] , [ ] , [ ] , [ ] , [ ] ] Expected output= > [ [ 1 , 2 , 3 ] , [ 1 , 3 , 2 ] , [ 2 , 1 , 3 ] , [ 2 ... | def permute ( nums ) : l= [ ] s=list ( ) ans= [ ] return helper ( nums , s , l ) def helper ( nums , s , l ) : if not nums : print ( l ) s.append ( l ) else : for i in range ( len ( nums ) ) : c=nums [ i ] l.append ( c ) nums.pop ( i ) helper ( nums , s , l ) nums.insert ( i , c ) l.pop ( ) return sprint ( permute ( [ ... | Permutation Leetcode |
Python | I want to draw a triple bar graph with three different dataframes using matplotLibDF1DF2DF3I am trying to use this piece of code but this is giving error as for this data needs to be from same dataframe | index | Number A | 110 B | 22 D | 52 index | NumberA | 100B | 22C | 52 index | Number A | 90 B | 12 C | 10 ax=DF1 [ [ `` Number '' ] ] .DF2 [ [ `` Number '' ] ] .DF3 [ [ `` Number '' ] ] .plot ( kind ='bar ' , log=True , title = `` BarGraph '' , figsize= ( 15,10 ) , legend=True , fontsize=10 ) ax.set_xlabel ( `` Index ... | How can I draw a bar graph from three different data frames using matplotlib ? |
Python | I 've built a simple scrapy spider running on scrapinghub : The problem I am facing is that the multiple_locs_url response.css returns an empty array despite me seeing it in the markup on the browser side . I checked with scrapy shell and scrapy shell does not see the markup . I guess this is due to the markup being re... | class ExtractionSpider ( scrapy.Spider ) : name = `` extraction '' allowed_domains = [ 'domain ' ] start_urls = [ 'http : //somedomainstart ' ] user_agent = `` Mozilla/5.0 ( Windows NT 10.0 ; Win64 ; x64 ) AppleWebKit/537.36 ( KHTML , like Gecko ) Chrome/61.0.3163.100 Safari/537.36 '' def parse ( self , response ) : ur... | Scrapy does not fetch markup on response.css |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.