lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Python
In my question a few minutes ago , I asked about how to print using python 's str.format printing , when the strings are stored in an array.Then answer was clearly unpack the list , like this : But if I always want the center hexagon to have printed inside the first item in the array : letters [ 0 ] , how can I mix unp...
# note that I had to play with the whitespace because the { } text is 2 characters , while its replacement is always onehex_string = r '' ' _____ / \ / \ , -- -- ( { } ) -- -- . / \ / \ / { } \_____/ { } \ \ / \ / \ / \ / ) -- -- ( { } ) -- -- ( / \ / \ / \_____/ \ \ { } / \ { } / \ / \ / ` -- -- ( { } ) -- -- ' \ / \_...
String format printing with python3 : print from unpacked array *some* of the time
Python
I was writing a small file utility earlier , and ran into an issue with passing by reference . After reading How do I pass a variable by reference ? , I set the variable I wanted to pass through as an argument and also as the return value . Within the code below , it is the line : where diff is the variable I wished to...
diff = compareDir ( path0 , path0List , path1 , path1List , diff ) def comparePaths ( path0 , path1 ) : path0List = os.listdir ( path0 ) path1List = os.listdir ( path1 ) diff = False diff = compareDir ( path0 , path0List , path1 , path1List , diff ) print ( ) diff = compareDir ( path1 , path1List , path0 , path0List , ...
Pythonic way to maintain variable assignment
Python
I have two sources with equatorial coordinates ( ra , dec ) and ( ra_0 , dec_0 ) located at distances r and r_0 , and I need to calculate the 3D distance between them.I use two approaches that should give the same result as far as I understand , but do not.The first approach is to apply astropy 's separation_3d functio...
91.3427173002 pc93.8470493776 pc from astropy.coordinates import SkyCoordfrom astropy import units as uimport numpy as np # Define some coordinates and distances for the sources.c1 = SkyCoord ( ra=9.7*u.degree , dec=-50.6*u.degree , distance=1500.3*u.pc ) c2 = SkyCoord ( ra=7.5*u.degree , dec=-47.6*u.degree , distance=...
Ca n't reproduce distance value between sources obtained with astropy
Python
I have a 32x32x3 image , say for example one of the cifar10 images in keras.Now , say I want to do some manipulation . First , to make sure I am doing things right , I was trying to copy the image ( that is not I want to do , so please do n't tell me how to copy the image without doing three loops , I need the three lo...
from keras.datasets import cifar10import matplotlib.pyplot as plt ( X_train , Y_train ) , ( X_test , Y_test ) = cifar10.load_data ( ) im = numpy.reshape ( X_train [ 0 ] , ( 3 , 32 , 32 ) ) im = im.transpose ( 1,2,0 ) imC = numpy.zeros ( ( 32,32,3 ) ) for k in range ( 3 ) : for row in range ( 0,32 ) : for col in range (...
Equal arrays but not the same visually
Python
Is there a method to find all functions that were defined in a python environment ? For instance , if I had some_command_here would return test
def test : pass
Finding All Defined Functions in Python Environment
Python
I would like to perform a rolling average but with a window that only has a finite 'vision ' in x. I would like something similar to what I have below , but I want a window range that based on the x value rather than position index.While doing this within pandas is preferred numpy/scipy equivalents are also OKSo I woul...
import numpy as np import pandas as pd x_val = [ 1,2,4,8,16,32,64,128,256,512 ] y_val = [ x+np.random.random ( ) *200 for x in x_val ] df = pd.DataFrame ( data= { ' x ' : x_val , ' y ' : y_val } ) df.set_index ( ' x ' , inplace=True ) df.plot ( ) df.rolling ( 1 , win_type='gaussian ' ) .mean ( std=2 ) .plot ( )
How to have pandas perform a rolling average on a non-uniform x-grid
Python
I have a Python set consisting of several values and I want to use method chaining like this : but g becomes empty . However , it works without chaining : Can somebody explain me this behaviour ?
> > > f = { 1 , 2 , 3 } > > > g = f.copy ( ) .discard ( 3 ) > > > g > > > > > > g = f.copy ( ) > > > g { 1 , 2 , 3 } > > > g.discard ( 3 ) > > > g { 1 , 2 }
Methods do n't chain in Python set
Python
I have the dataframe above . My goal is to replace all mixed word/number combo 's WITHOUT hyphens - e.g . 1A1619I or BL171111 or A13B but NOT 1-22-2001 or A-1-24 with the letter M. I have attempted to use the code below via identify letter/number combinations using regex and storing in dictionaryBut I get this outputwh...
dataframe = pd.DataFrame ( { 'Date ' : [ 'This 1A1619 person BL171111 the A-1-24 ' , 'dont Z112 but NOT 1-22-2001 ' , 'mix : 1A25629Q88 or A13B ok ' ] , 'IDs ' : [ 'A11 ' , 'B22 ' , 'C33 ' ] , } ) Date IDs0 This 1A1619 person BL171111 the A-1-24 A111 dont Z112 but NOT 1-22-2001 B222 mix : 1A25629Q88 or A13B ok C33 data...
replace words and strings pandas
Python
I have a function : However , my intention is for the function to take only one argument ( either title OR pageid ) . For example , delete ( title= '' MyPage '' ) or delete ( pageid=53342 ) are valid , while delete ( title= '' MyPage '' , pageid=53342 ) , is not . Zero arguments can not be passed . How would I go about...
def delete ( title=None , pageid=None ) : # Deletes the page given , either by its title or ID ... pass
Python function that takes one compulsory argument from two choices
Python
Using GStreamer ( gst-launch1.0 ) , I am multiplexing two streamsOne contains the silence Other contains the audio speechBut the problem is that the quality of the audio output is not good . The voice is distorted . I need your help to improve the quality of the audio and here is my gstreamer command with parameters : ...
gst-launch-1.0 -v udpsrc name='src1 ' caps= '' application/x-rtp '' port= ! rtppcmudepay ! mulawdec ! audioconvert ! audioresample ! mix . udpsrc name='src2 ' caps= '' application/x-rtp '' port= ! rtppcmudepay ! mulawdec ! audioconvert ! audioresample ! mix . audiomixer name=mix start-time-selection=1 ! audioresample !...
How to improve the quality of the audio of RTMP stream after multiplexing two streams
Python
If , as a simplified example , I am writing a library to help people model populations I might have a class such as : where t0 is of type datetime . Now I want to provide a method to determine the population at a given time , whether that be a datetime or a float containing the number of seconds since t0 . Further , it...
class Population : def __init__ ( self , t0 , initial , growth ) : self.t0 = t0 , self.initial = initial self.growth = growth def at_raw ( self , t ) : if not isinstance ( t , collections.Iterable ) : t = numpy.array ( [ t ] ) return self.initial*numpy.exp ( self.growth*t ) def at_datetime ( self , t ) : if not isinsta...
Pythonic way of writing a library function which accepts multiple types ?
Python
How to print an index with a same name with a newline delimitted by priting the Index Name as a header : i have below list values , where i have Art , Science and Geology having multiple lines i want all the lines get printed with a same index value with a newline separator.Below is processed as abovethe output i would...
file = open ( 'student.txt ' ) for line in file : fields = line.strip ( ) .split ( ) print ( fields ) [ 'Jullu ' , '18 ' , 'Art ' ] [ 'sean ' , '25 ' , 'Art ' ] [ 'Rubeena ' , '18 ' , 'Science ' ] [ 'Kareen ' , '18 ' , 'Science ' ] [ 'Rene ' , '18 ' , 'Geology ' ] [ 'Babu ' , '18 ' , 'Geology ' ] [ 'Riggu ' , '18 ' , '...
How to get the entire line printed with Same Index name
Python
When using only Optional or ZeroOrMore , pyparsing seems to enter in an infinite loop . The following code work but the part `` # Should work with pp.Optional ( ) '' should indeed be Optional and not OneOrMore . Should I put some sort of stopOn in this case ? The dictionary is shown below : In which [ expr ] means Opti...
[ PINS numPins ; [ – pinName + NET netName [ + SPECIAL ] [ + DIRECTION { INPUT | OUTPUT | INOUT | FEEDTHRU } ] [ + NETEXPR `` netExprPropName defaultNetName '' ] [ + SUPPLYSENSITIVITY powerPinName ] [ + GROUNDSENSITIVITY groundPinName ] [ + USE { SIGNAL | POWER | GROUND | CLOCK | TIEOFF | ANALOG | SCAN | RESET } ] [ + ...
PyParsing Optional ( ) hanging
Python
I am trying to understand how the for x in y statement works in python . I found the documentation here : https : //docs.python.org/3/reference/compound_stmts.html # for . It says that the expression y is evaluated once and must yield an iterable object.The following code prints the numbers 1,2,3,4,5 even though my cla...
class myclass : def __init__ ( self ) : self.x = [ 1,2,3,4,5 ] def __getitem__ ( self , index ) : return self.x [ index ] m = myclass ( ) for i in m : print ( i )
Built in iter ( ) function and for statement
Python
First of all I wanted to say that my title is probably not describing my question correctly . I do n't know how the process I am trying to accomplish is called , which made searching for a solution on stackoverflow or google very difficult . A hint regarding this could already help me a lot ! What I currently have are ...
List1 = [ [ a , b ] , [ c , d , e ] , [ f ] ] List2 = [ [ g , h , i ] , [ j ] , [ k , l ] ] [ a , b ] - > [ g , h , i ] [ a ] - > [ g ] [ a ] - > [ h ] [ a ] - > [ i ] [ b ] - > [ g ] [ b ] - > [ h ] [ b ] - > [ i ] List3 = [ [ a , g ] , [ a , h ] , [ a , i ] , [ b , g ] , ... ]
Python : Combination in lists of lists ( ? )
Python
I 've written a simple AWS step functions workflow with a single step : My goal is to have the train input pulled from the execution JSON provided at runtime . When I execute the workflow ( from the step functions console ) , providing the JSON { `` app_id '' : `` My App ID '' } the tuning step does not get the right d...
from stepfunctions.inputs import ExecutionInputfrom stepfunctions.steps import Chain , TuningStepfrom stepfunctions.workflow import Workflowimport train_utilsdef main ( ) : workflow_execution_role = 'arn : aws : iam : :MY ARN ' execution_input = ExecutionInput ( schema= { 'app_id ' : str } ) estimator = train_utils.get...
AWS - Step functions , use execution input within a TuningStep
Python
I 'm a bit annoyed with myself because I ca n't understand why one solution to a problem worked but another did n't . As in , it points to a deficient understanding of ( basic ) pandas on my part , and that makes me mad ! Anyway , my problem was simple : I had a list of 'bad ' values ( 'bad_index ' ) ; these correspond...
bad_index = [ 2 , 7 , 8 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 , 21 , 22 , 24 , 29 ] for i in bad_index : dataclean2 = dataclean1.drop ( [ i ] ) .reset_index ( level = 0 , drop = True ) bad_index = [ 2 , 7 , 8 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 , 21 , 22 , 24 , 29 ] data_clean2 = data_clean1.drop ( [ x ...
List comprehension works but not for loop––why ?
Python
I 'm currently having a small side project in which I want to sort a 20GB file on my machine as fast as possible . The idea is to chunk the file , sort the chunks , merge the chunks . I just used pyenv to time the radixsort code with different Python versions and saw that 2.7.18 is way faster than 3.6.10 , 3.7.7 , 3.8....
import osdef chunk_data ( filepath , prefixes ) : `` '' '' Pre-sort and chunk the content of filepath according to the prefixes . Parameters -- -- -- -- -- filepath : str Path to a text file which should get sorted . Each line contains a string which has at least 2 characters and the first two characters are guaranteed...
Did I/O become slower since Python 2.7 ?
Python
A user asked ( Keyerror while using pandas in PYTHON 2.7 ) why he was having a KeyError while looking in a dictionary and how he could avoid this exception.As an answer , I suggested him to check for the keys in the dictionary before . So , if he needed all the keys [ 'key_a ' , 'key_b ' , 'key_c ' ] in the dictionary ...
if not all ( [ x in dictionary for x in [ 'key_a ' , 'key_b ' , 'key_c ' ] ] ) : continue
Am I using ` all ` correctly ?
Python
I am looking for a way to sort my array of array which has a complex structure : I woul 'd like to sort it by the last elements meaning ( 56 , 3 , 54 and 42 , 6 ) .What I want to get it is that : I have already tried : L.sort ( key=lambda x : x [ 0 ] [ 0 ] [ 2 ] ) but it does n't work ... I have seen those advices but ...
L= [ [ [ [ 1,1,1,1,1,1,1 ] ,1,56 ] , [ [ 6,6,6,6,6,6,6 ] ,1,3 ] , [ [ 3,3,3,3,3,3,3 ] ,1,54 ] ] , [ [ [ 2,2,2,2,2,2,2 ] ,2,42 ] , [ [ 5,5,5,5,5,5,5 ] ,2,6 ] ] ] L= [ [ [ [ 6,6,6,6,6,6,6 ] ,1,3 ] , [ [ 3,3,3,3,3,3,3 ] ,1,54 ] , [ [ 1,1,1,1,1,1,1 ] ,1,56 ] ] , [ [ [ 5,5,5,5,5,5,5 ] ,2,6 ] , [ [ 2,2,2,2,2,2,2 ] ,2,42 ] ] ...
Sorting a complex structure of array of array
Python
It seems that whatever I throw in input in hopes to break it , python just keeps one upping me . It like knows what I 'm trying to achieve here and goes `` nope ''
> > > input ( `` input '' ) input > ? a ' a ' > > > input ( `` input '' ) input > ? ' a '' ' a '' > > > input ( `` input '' ) input > ? ' '' a'\ ' '' a ' > > > input ( `` input '' ) input > ? \ ' '' a'\\\ ' '' a ' > > > input ( `` input '' ) input > ? `` ' a ' '' \ ' a ' > > > input ( `` input '' ) input > ? `` `` a ' ...
is it possible to make input ( ) throw errors ?
Python
I 'm trying to understand what 's the execution complexity of the iloc function in pandas.I read the following Stack Exchange thread ( Pandas DataFrame search is linear time or constant time ? ) that : '' accessing single row by index ( index is sorted and unique ) should have runtime O ( m ) where m < < n_rows '' ment...
import pandas as pd > > > a = pd.DataFrame ( [ [ 1,2,3 ] , [ 1,3,4 ] , [ 2,3,4 ] , [ 2,4,5 ] ] , columns= [ ' a ' , ' b ' , ' c ' ] ) > > > a = a.set_index ( ' a ' ) .sort_index ( ) > > > a b ca1 3 41 4 52 2 32 3 4 > > > a.iloc [ [ 0,1,2,3 ] ] b ca1 3 41 4 52 2 32 3 4 > > > a.drop ( [ 1 ] ) .iloc [ [ 0,1 ] ] b ca2 2 32...
What 's the computational complexity of .iloc ( ) in pandas dataframes ?
Python
Can anyone explain why the following example does not raise the Exception ? This just returns : Where as the same code without the return 'bar ' statement throws the exception :
def foo ( ) : try : 0/0 except Exception : print ( 'in except ' ) raise finally : print ( 'in finally ' ) return 'bar'my_var = foo ( ) print ( my_var ) in exceptin finallybar in exceptin finallyTraceback ( most recent call last ) : File `` test.py '' , line 10 , in < module > my_var = foo ( ) File `` test.py '' , line ...
python exception not raised if finally returns value
Python
I have a big list of lists , something like And I 'd like to calculate the average of 50 values each in each column . I 'd like to get something like : But instead of values from 1-1000 I have several text files with one column each , and I packed them together in the np.array with I tried looping over parts of the lis...
import numpy as npnp.array ( [ range ( 1,1000 ) , range ( 1,1000 ) , range ( 1,1000 ) ] ) np.array ( [ [ np.mean ( range ( 1,50 ) ) , np.mean ( range ( 51,100 ) ) , ... ] , [ [ np.mean ( range ( 1,50 ) ) , np.mean ( range ( 51,100 ) ) , ... ] , ... ] ) average_list = np.array ( [ np.genfromtxt ( `` 1.txt '' ) , np.genf...
Average over parts in list of lists
Python
I need to replace values in the dataframe column x . The result should look like x_new . So in detail I have to keep the values in the x column where y is 1 and 255 . Between 1 and 255 I must replace the x values with the value where y is 1 . The values between 255 and 1 should stay the same . So how can I get the colu...
x y z x_new12.28 1 1 12.2811.99 0 1 12.2811.50 0 1 12.2811.20 0 1 12.2811.01 0 1 12.28 9.74 255 0 9.7413.80 0 0 13.8015.2 0 0 15.217.8 0 0 17.812.1 1 1 12.111.9 0 1 12.111.7 0 1 12.111.2 0 1 12.110.3 255 0 10.3
Replace values in dataframe column depending on another column with condition
Python
for dynamic values sometimes the value will be keep repeating , say if a variable here { 'man ' : 'tim ' , 'age ' : ' 2 ' , ' h ' : ' 5 ' , ' w ' : '40 ' } dictionary set repeat twice these are dynamic value.How can I stop repeating this , so list will not contain any repeated dictionary before rendering it to template...
table = [ { 'man ' : 'tim ' , 'age ' : ' 2 ' , ' h ' : ' 5 ' , ' w ' : '40 ' } , { 'man ' : 'jim ' , 'age ' : ' 4 ' , ' h ' : ' 3 ' , ' w ' : '20 ' } , { 'man ' : 'jon ' , 'age ' : '24 ' , ' h ' : ' 5 ' , ' w ' : '80 ' } , { 'man ' : 'tim ' , 'age ' : ' 2 ' , ' h ' : ' 5 ' , ' w ' : '40 ' } , { 'man ' : 'tto ' , 'age '...
How can I delete a repeated dictionary in list ?
Python
My general problem is that I have a dataframe where columns correspond to feature values . There is also a date column in the dataframe . Each feature column may have missing NaN values . I want to fill a column with some fill logic such as `` fill_mean '' or `` fill zero '' . But I do not want to just apply the fill l...
# assume ts_values is a time series where the first value in the list is the oldest value and the last value in the list is the most recent.ts_values = [ 17.0 , np.NaN , 12.0 , np.NaN , 18.0 ] nan_inds = np.argwhere ( np.isnan ( ts_values ) ) for nan_ind in nan_inds : nan_ind_value = nan_ind [ 0 ] ts_values [ nan_ind_v...
How to efficiently fill a time series ?
Python
Google Maps results are often displayed thus : Another variation : And another : Notice the variation in the placement of the \n characters.I 'm looking to extract the first X lines as address , and the last line as phone number . A regex such as ( .*\n.* ) \n ( . * ) would suffice for the first example , but falls sho...
'\n113 W 5th St\nEureka , MO , United States\n ( 636 ) 938-9310\n ' 'Clayton Village Shopping Center , 14856 Clayton Rd\nChesterfield , MO , United States\n ( 636 ) 227-2844 ' 'Wildwood , MO\nUnited States\n ( 636 ) 458-7707 '
How to Python split by a character yet maintain that character ?
Python
I am reading http : //docs.python.org/2/tutorial/modules.html # more-on-modules and wonder if the following is correct : Modules can import other modules . It is customary but not required to place all import statements at the beginning of a module ( or script , for that matter ) . The imported module names are placed ...
> > > def foo ( ) : import sys ... > > > foo ( ) > > > sys.pathTraceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > NameError : name 'sys ' is not defined
Bug in Python 's documentation ?
Python
Assuming I have following data set Now I want to replace the value of column B in df by dct I know I can dodf.B.map ( dct ) .fillna ( df.B ) to get the expected out put , but when I test with replace ( which is more straightforward base on my thinking ) , I failed The out put show as below Which is different from the I...
lst = [ ' u ' , ' v ' , ' w ' , ' x ' , ' y ' ] lst_rev = list ( reversed ( lst ) ) dct = dict ( zip ( lst , lst_rev ) ) df = pd.DataFrame ( { ' A ' : [ ' a ' , ' b ' , ' a ' , ' c ' , ' a ' ] , ' B ' : lst } , dtype='category ' ) df.B.replace ( dct ) Out [ 132 ] : 0 u1 v2 w3 v4 uName : B , dtype : object df.B.map ( dc...
Is replace row-wise and will overwrite the value within the dict twice ?
Python
I 'm trying to send an HTTPS request through an HTTPS tunnel . That is , my proxy expects HTTPS for the CONNECT . It also expects a client certificate.I 'm using Requests ' proxy features.This works , but with some limitations : I can only set client certificates for the TLS connection with the proxy , not for the exte...
import requestsurl = `` https : //some.external.com/endpoint '' with requests.Session ( ) as session : response = session.get ( url , proxies= { `` https '' : `` https : //proxy.host:4443 '' } , # client certificates expected by proxy cert= ( cert_path , key_path ) , verify= '' /home/savior/proxy-ca-bundle.pem '' , ) w...
Set CA bundle for requests going through HTTPS tunnel
Python
I am running a couple of nosetests with test cases in different modules ( files ) each containing different tests . I want to define a function/method that is only called once during the execution with nosetest . I looked at the documentation ( and e.g . here ) and see there are methods like setup_module etc . - but wh...
class TestSuite ( basicsuite.BasicSuite ) : def setup_module ( self ) : print ( `` MODULE '' ) ...
How to define a setup method only called once during testing with nosetest ?
Python
Here is a simplified example of my problem . I thought that these functions would have exactly the same behavior : But in reality f1 ( l ) works fine when f2 ( l ) collapses with the exception : So the question is why is it so and is it possible to use ternary operator that returns one of the functions at all ?
def f1 ( l ) : if type ( l [ 0 ] [ 0 ] ) ==list : f=lambda x : x [ 0 ] [ 0 ] else : f=lambda x : x [ 0 ] l.sort ( key=f , reverse=True ) def f2 ( l ) : f=lambda x : x [ 0 ] [ 0 ] if type ( l [ 0 ] [ 0 ] ) ==list else lambda x : x [ 0 ] l.sort ( key=f , reverse=True ) l= [ [ 1,2 ] , [ 3,4 ] ] IndexError : list index out...
Strange behavior : ternary operator for functions
Python
I 've been breaking my head on this and I ca n't seem to find a solution to the problem . I use an enum to manage my access in a flask server . Short story I need the enum to return a default value if a non-existent enum value is queried . First I created a meta class for the enum : You can see I exclude the _subs_tree...
class AuthAccessMeta ( enum.EnumMeta ) : def __getattr__ ( self , item ) : try : return super ( ) .__getattr__ ( item ) except Exception as _ : if self == AuthAccess and item not in [ '_subs_tree ' ] : Loggers.SYS.warn ( 'Access { } doesn\'t exist , substituting with MISSING . '.format ( item ) ) return AuthAccess.MISS...
Python enum meta making typing module crash
Python
Suppose , I have a list of 1,1and it can take either + or - sign . So the possible combination would be 2 to the power 2 . Similarly , I have a list of 1,1,1and it can take either + or - sign . So the possible combination would be 2 to the power 3.In python , how can I do that using itertools or any other methods . Any...
1 1 1 -1-1 1-1 -1 -1 1 -1-1 1 1 1 1 1 1 -1 1-1 -1 -1 1 1 -1 1 -1 -1-1 -1 1
all possible phase combination
Python
I fully understand what is being passed to self in this example . I 'm very confused on how it is being passed to self internally . Could someone help me understand ?
class Cars : def __init__ ( self , model , engine , doors ) : self.model = model self.engine = engine self.doors = doorstesla = Cars ( 'Model S ' , 'Electric ' , 'Four door ' ) ford = Cars ( 'Mustang ' , 'v8 ' , 'Two door ' )
Understanding Self Internally in Python
Python
I have a list of values , and a list of indices , and I need to remove the elements that the indices point to.This is my solution , but I do n't like the implementation as it requires to import packages , does n't work when the values contain maxint , and iterate over the values multiple times . Any better solutions ?
def remove_abnormalities ( values , indices ) : v = list ( values ) for i in indices : v [ i ] = sys.maxint return filter ( lambda i : i ! = sys.maxint , v )
Remove multiple elements from a list of index with Python
Python
I am trying do write a quick simulation program . As a first step , I want to take an input and do the following : Use this input to find the corresponding value from the dict , say Igot 29.0 in my example.I would now like to generate 3 values to the left and 3 values to the right . Ideally the output should be 27.5 , ...
# ! /usr/bin/pythondef getids ( tk ) : tk=tk.lower ( ) r=map ( lambda x : x/10.0 , range ( 0,6 ) ) val= { 'PPP':29 } val= { k.lower ( ) : v for k , v in val.items ( ) } if tk in val : stk_price=val [ tk ] for i in r : stk_price=stk_price + i print ( stk_price ) getids ( 'PPP ' ) 29.029.129.329.630.030.5
generating 10 values in python around one value
Python
Full code example : When trying to execute test , getting error : Is it possible to access static fields from the decorated class ?
def decorator ( class_ ) : class Wrapper : def __init__ ( self , *args , **kwargs ) : self.instance = class_ ( *args , **kwargs ) @ classmethod def __getattr__ ( cls , attr ) : return getattr ( class_ , attr ) return Wrapper @ decoratorclass ClassTest : static_var = `` some value '' class TestSomething : def test_decor...
Accessing static fields from the decorated class
Python
I have difficulty understanding the last part ( in bold ) from Python in a Nutshell Per-Instance Methods An instance can have instance-specific bindings for all attributes , including callable attributes ( methods ) . For a method , just like for any other attribute ( except those bound to overriding descriptors ) , an...
def fake_get_item ( idx ) : return idxclass MyClass ( object ) : passn = MyClass ( ) n.__getitem__ = fake_get_itemprint ( n [ 23 ] ) # results in : # Traceback ( most recent call last ) : # File `` < stdin > '' , line 1 , in ? # TypeError : unindexable object
`` implicit uses of special methods always rely on the class-level binding of the special method ''
Python
How do I delete buckets in a batch ? Here 's what i 've tried.Technically it works because the buckets get deleted , however i 'm not convinced i 'm sending a single batch request . It looks like i 'm sending one request per bucket.Compare the above code to a batch request in Google Cloud DatastoreYou can see that i 'm...
def deleteAllBuckets ( ) : batch = storage_client.batch ( ) with batch : for bucket in storage_client.list_buckets ( ) : bucket.delete ( ) def deleteAllEntities ( ) : query = datastore_client.query ( kind= '' Charge '' ) queryIter = query.fetch ( ) batch = datastore_client.batch ( ) with batch : for entity in queryIter...
How to batch delete buckets
Python
This is the MRE of my code : Now , when I run this using cmd or IDLE , it runs perfectly . But when I make its executable ( the command I used was `` pyinstaller -- onefile { name of python file } '' ) using pyinstaller , there appears a warning on the cmd window : `` WARNING : Hidden import `` pygame._view '' not foun...
import pygamepygame.init ( ) screen = pygame.display.set_mode ( ( 800 , 600 ) ) screen.fill ( ( 255 , 215 , 0 ) ) x_coordinate = 330y_coordinate = 250font = pygame.font.SysFont ( 'comicsans ' , 30 , False , False ) writing = font.render ( `` this is a test '' , 1 , ( 0,0,0 ) ) running = Truewhile running : for event in...
How to fix `` WARNING : Hidden import `` pygame._view '' not found ! '' when converting .py to .exe using PyInstaller ?
Python
I have two ndarrays with shapes : I need to multiply A and B such that I get a new ndarray : Another way to think of it is that each row of vector B is multiplied along axis=-2 of A , which results in a new 1,32,512,640 cube . Each row of B can be looped over forming 1,32,512,640 cubes , which can then be used to build...
A = ( 32,512,640 ) B = ( 4,512 ) C = ( 4,32,512,640 ) # Sample inputs , where the dimensions are n't necessarily knowna = np.arange ( 32*512*465 , dtype='f4 ' ) .reshape ( ( 32,512,465 ) ) b = np.ones ( ( 4,512 ) , dtype='f4 ' ) # Using a loopd = [ ] for row in b : d.append ( np.expand_dims ( row [ None , : , None ] *a...
Most Pythonic way to multiply these two vectors ?
Python
I am a beginner and have a confusion when I am learning python . If I have the following python code : Y will be shown to be array ( [ 2 , 0 , 0 ] ) However , if I do the following : Y is still array ( [ 1,0,0 ] ) What is going on ?
import numpy as npX = np.array ( [ 1,0,0 ] ) Y = XX [ 0 ] = 2print Y import numpy as npX = np.array ( [ 1,0,0 ] ) Y = XX = 2*Xprint Y
Python confusion -- convention , name and value
Python
So I have two value columns and two weight columns in a Pandas DataFrame , and I want to generate a third column that is the grouped by , weighted , average of those two columns.So for : I 'd want to accomplish : I 've already accomplished this using just arithmetic operators like this : But I want to generalize it to ...
df = pd.DataFrame ( { 'category ' : [ ' a ' , ' a ' , ' b ' , ' b ' ] , 'var1 ' : np.random.randint ( 0,100,4 ) , 'var2 ' : np.random.randint ( 0,100,4 ) , 'weights1 ' : np.random.random ( 4 ) , 'weights2 ' : np.random.random ( 4 ) } ) df category var1 var2 weights1 weights20 a 84 45 0.955234 0.7298621 a 49 5 0.225470 ...
Grouped By , Weighted , Column Averages in Pandas
Python
I 'm interested in the number 'm ' times within the last ' n ' events that a condition is met , grouped by person or user . Specifically , I 'm interested in whether a player is used to playing in a given class , or 'category ' , based on how many of their last few matches ( rather than any matches ) were played at or ...
import pandas as pdpd.__version__ # ' 0.23.4'match = [ ' a ' , ' a ' , ' a ' , ' b ' , ' b ' , ' b ' , ' c ' , ' c ' , ' c ' , ' c ' , 'd ' , 'd ' , 'd ' , ' e ' , ' e ' , ' e ' , ' e ' ] category = [ 3 , 3 , 3 , 2 , 2 , 2 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 2 , 2 , 2 , 2 ] player = [ 'bar ' , 'baz ' , 'chaz ' , 'baz ' , 'ch...
Rolling m out of n most recent occurences of condition in pandas
Python
I have two lists : I want to return a list with objects only from list1 but if the same important_key1 and important_key2 is in any element in list2 I want this element from list2.So the output should be : It is not complicated to do it by two or three loops but I wonder whether there is a simple way by using list comp...
list1 = [ { 'sth ' : 13 , 'important_key1 ' : 'AA ' , 'important_key2 ' : ' 3 ' } , { 'oh ! ' : 14 , 'important_key1 ' : 'FF ' , 'important_key2 ' : ' 4 ' } , { 'sth_else ' : 'abc ' , 'important_key1 ' : 'ZZ ' , 'important_key2 ' : ' 5 ' } ] list2 = [ { 'why-not ' : 'tAk ' , 'important_key1 ' : 'GG ' , 'important_key2 ...
Python3 How to join two lists of dicts by unique keys
Python
Do the below 2 import statements have some difference ? Or just the same thing ?
from package import *import package
Any difference between these 2 imports ?
Python
I 'm trying to parse a large text file that has inconsistent spacing and repeating lines . A lot of the text in the file I do not need , but for example in one line I may need 6 items from it , some separated by commas , some separated by space . Example Line : 1 23456 John , Doe 366 : F.7What I want ( in CSV ) : 1 245...
import csvdef is_page_header ( line ) : return ( line [ 0 ] == ' 1 ' ) and ( `` RUN DATE : '' not in line ) def read_header ( inFile ) : while True : line = inFile.readline ( ) if '************************ ' in line : breakdef is_rec_start ( line ) : try : x = int ( line [ 0:6 ] ) return True except : return Falsefilen...
Parsing a text file with random spacing and repeating text ?
Python
I have a file containing multiple lines starting with `` 1ECLI H -- - 12.345 ... .. '' . I want to remove a space between I and H and add R/S/T upon iteration of the H pattern . for eg . H810 if repeated in consecutive three lines , it should get added with a letter R , S ( second iteration ) , T ( third iteration ) . ...
1ECLI H813 98 7.529 8.326 9.2671ECLI H813 99 7.427 8.470 9.2511ECLI C814 100 7.621 8.513 9.2631ECLI H814 101 7.607 8.617 9.2891ECLI H814 102 7.633 8.489 9.1561ECLI H814 103 7.721 8.509 9.3051ECLI C74 104 8.164 8.733 10.7401ECLI H74R 105 8.247 8.690 10.799 1ECLI H813R 98 7.529 8.326 9.2671ECLI H813S 99 7.427 8.470 9.251...
pattern match and replace the string with if else loop
Python
In Keras , why is it that input_shape does not include the batch dimension when passed as an argument to layers like Dense but DOES include the batch dimension when input_shape is passed to the build method of a model ? Is this a conscious choice of API design ? If it is , why ?
import tensorflow as tffrom tensorflow.keras.layers import Denseif __name__ == `` __main__ '' : model1 = tf.keras.Sequential ( [ Dense ( 1 , input_shape= [ 10 ] ) ] ) model1.summary ( ) model2 = tf.keras.Sequential ( [ Dense ( 1 ) ] ) model2.build ( input_shape= [ None , 10 ] ) # why [ None , 10 ] and not [ 10 ] ? mode...
Why is it that ` input_shape ` does not include the batch dimension when passed as an argument to the ` Dense ` layer ?
Python
I have tried the code below : the purpose is to generate a dictionary where each key has a list as a value . The first iteration goes well and generates the item as I want it , but the second loop , the nested for loop , does n't generate the list as expected . Please help me with this simple code . There must be somet...
schop = [ 1 , 3 , 1 , 5 , 6 , 2 , 1 , 4 , 3 , 5 , 6 , 6 , 2 , 2 , 3 , 4 , 4 , 5 ] mop = [ 1 , 1 , 2 , 1 , 1 , 1 , 3 , 1 , 2 , 2 , 2 , 3 , 2 , 3 , 3 , 2 , 3 , 3 ] mlist = [ `` 1 '' , '' 2 '' , '' 3 '' ] wmlist=zip ( mop , schop ) title = { } for m in mlist : m = int ( m ) k= [ ] for a , b in wmlist : if a == m : k.appen...
cant iterate nested for loop as wanted -python -maybe a simple mistake
Python
I 'm looking for some help understanding best practices regarding dictionaries in Python . I have an example below : Obviously , the two functions achieve the same goal , but via different means . Could someone help me understand the subtle difference between the two , and what the 'best ' way to go on about this would...
def convert_to_celsius ( temp , source ) : conversion_dict = { 'kelvin ' : temp - 273.15 , 'romer ' : ( temp - 7.5 ) * 40 / 21 } return conversion_dict [ source ] def convert_to_celsius_lambda ( temp , source ) : conversion_dict = { 'kelvin ' : lambda x : x - 273.15 , 'romer ' : lambda x : ( x - 7.5 ) * 40 / 21 } retur...
Recommended usage of Python dictionary , functions as values
Python
I have a large dataset where each line represents the value of a certain type ( think a sensor ) for a time interval ( between start and end ) .It looks like this : I want to turn it into a daily time-indexed frame like this : ( Note that we can not make any assumption regarding the interval : they should be contiguous...
start end type value2015-01-01 2015-01-05 1 32015-01-06 2015-01-08 1 22015-01-05 2015-01-08 3 32015-01-13 2015-01-16 2 1 day type value2015-01-01 1 32015-01-02 1 32015-01-03 1 32015-01-04 1 32015-01-05 1 32015-01-06 1 22015-01-07 1 22015-01-08 1 22015-01-05 3 32015-01-16 3 32015-01-07 3 32015-01-08 3 32015-01-13 2 1201...
Performance issue turning rows with start - end into a dataframe with TimeIndex
Python
I know accessing the attributes of Foo through an instance will call the __getattribute__ ( ) method , but what if I access this attribute directly through the class ? If a function is called , I want to set a breakpoint in it so that the breakpoint can be triggered when accessing this property through a class in my pr...
class Foo : age = 18print ( Foo.age ) # I am curious what method is called
What method does Python call when I access an attribute of a class via the class name ?
Python
Python 2 interned `` all name-character '' strings up to 20 code points long : In Python 3.7 , this number has seemingly increased to 4096 : Firstly : what motivated this change ? Secondly , where in CPython is this limit established ? I can ' find a reference to that number for the life of me . I do n't see it in PyUn...
Python 2.7.15 ( default , Feb 9 2019 , 16:01:32 ) [ GCC 4.2.1 Compatible Apple LLVM 10.0.0 ( clang-1000.10.44.4 ) ] on darwinType `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > ' a ' * 20 is 'aaaaaaaaaaaaaaaaaaaa'True > > > ' a ' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'False Python 3.7...
Change in max length of interned strings in CPython
Python
I am dealing with RF signals that sometimes have noise spikes.The input is something like this:00000001111100011110001111100001110000001000001111000000111001111000 Before parsing the data in the signal , I need to remove the spike bits , that are 0 's and 1 's sequence with a lenght lower than ( in this example ) 3.So ...
self.re_one_spikes = re.compile ( `` ( ? : [ ^1 ] ) ( ? P < spike > 1 { 1 , % d } ) ( ? = [ ^1 ] ) '' % ( self._SHORTEST_BIT_LEN - 1 ) ) self.re_zero_spikes = re.compile ( `` ( ? : [ ^0 ] ) ( ? P < spike > 0 { 1 , % d } ) ( ? = [ ^0 ] ) '' % ( self._SHORTEST_BIT_LEN - 1 ) ) re.compile ( `` ( ? ! [ \1 ] ) ( [ 01 ] { 1,2...
Regex to remove bit signal noise spikes
Python
I am parsing JavaScript source files in python 3.5 . A loop checks out all commits from a github repository , and the script loops through all changed files . When a file is changed in two subsequent checkouts ( which means , it changed in the commit ) , the script can hang on the with ( open ... ) line for seconds , e...
test_data = `` ./sample.js '' for _ in range ( 10 ) : start1 = time.time ( ) with open ( file=test_data , mode= '' rb '' , buffering=1 ) as f : end1 = time.time ( ) start2 = time.time ( ) line_content = f.readlines ( ) # # Do some processing end2 = time.time ( ) print ( `` Processing file { } is done . `` .format ( tes...
Python hangs for too long on with open
Python
I have a small Python program that behaves differently in Python 3.7 and Python 3.8 . I 'm struggling to understand why . The # threading changelog for Python 3.8 does not explain this.Here 's the code : When I run this in Python 3.7.3 ( Debian Buster ) , I see the following output : The program exits on its own . I do...
import timefrom threading import Event , Threadclass StoppableWorker ( Thread ) : def __init__ ( self ) : super ( StoppableWorker , self ) .__init__ ( ) self.daemon = False self._stop_event = Event ( ) def join ( self , *args , **kwargs ) : self._stop_event.set ( ) print ( `` join called '' ) super ( StoppableWorker , ...
Difference in Python thread.join ( ) between Python 3.7 and 3.8
Python
I have a data frame with two columns : I need to count no of rows where numbers under column ones are divisible by 5 or numbers under column zeros are divisible by 3.As this is sub-section of a problem . I have prepared the data frame after cleaning and the data frame having 2 columns and 4369 no of rows.I have tried t...
ones zeros0 6 131 8 72 11 73 8 54 11 55 10 66 11 67 7 48 9 49 4 610 7 511 6 712 9 1013 14 314 7 715 7 716 9 717 7 1018 9 519 12 720 4 821 6 422 11 523 9 724 3 1025 7 426 6 1227 9 728 7 429 9 9 ... ... ... 4339 10 94340 7 104341 6 114342 4 64343 9 114344 5 114345 7 94346 9 54347 11 74348 9 104349 8 104350 6 54351 5 8435...
How to count no of rows in a data frame whose values divisible by 3 or 5 ?
Python
In a django app I 've created different models and everything looks okay until I try using data from two different models inside the same table.To sum it up : in the homepage , I need to create a table that contains data from both the models , ordered by date . The two models I need to display are the following . model...
class Document ( models.Model ) : number = models.CharField ( max_length=10 ) description = models.CharField ( max_length=50 ) assigned = models.BooleanField validity_date = models.DateField is_issued = models.BooleanFieldclass Program ( models.Model ) : name = models.CharField ( max_length=25 ) description = models.Ch...
How to display instances from two different django models on the same template , inside the same table ?
Python
When running IPython if you evaluate a semicolon you get a return value of the empty string , as shown below . Why ? My theory is that it 's IPython stripping out the line terminator in the statement but that still does n't explain why it returns a string.This also works in IPython for Python 3.Edit : Sorry , should ha...
$ ipythonPython 2.7.12 ( default , Oct 11 2016 , 05:24:00 ) Type `` copyright '' , `` credits '' or `` license '' for more information.IPython 5.1.0 -- An enhanced Interactive Python. ? - > Introduction and overview of IPython 's features. % quickref - > Quick reference.help - > Python 's own help system.object ? - > D...
Why does a semicolon return an empty string in IPython ?
Python
Say I have a list of strings : obj = [ 'One ' , 'Two ' , 'Three ' ] , how would I be able to turn each value in this list into a function where they all carry out very similar functions ? For example : Now I know you can define the functions beforehand and use a dictionary ( as shown below ) , but say I wanted many fun...
def one ( ) : print ( `` one '' ) def two ( ) : print ( `` two '' ) def three ( ) : print ( `` three '' ) import tkinter as tkdef one ( ) : print ( `` one '' ) def two ( ) : print ( `` two '' ) def three ( ) : print ( `` three '' ) obj = [ 'One ' , 'Two ' , 'Three ' ] func = { 'One ' : one , 'Two ' : two , 'Three ' : t...
Definining a function from a list
Python
I am reading a book and see tons of examples like this : Since \w means [ a-zA-Z0-9_ ] , \d means [ 0-9 ] , \d is subset of \w.So , are n't those `` \d '' s redundant ? Please someone confirm my understanding is correct as this drives me nut .
( ? P < email > [ \w\d.+- ] + # username @ ( [ \w\d. ] +\ . ) + # domain name prefix ( com|org|edu ) # limit the allowed top-level domains )
Is n't \d redundant in [ \w\d ] ?
Python
this line always gives a error- > TypeError : sorted expected 1 argument , got 2in fact the syntax of sorted is sorted ( iterable , key , reverse ) , in which key and reverse are optional , so according to this , second parameter i pass must go with key.and when i def my own funchere 200 automatically passed as y argum...
a= [ 1,2,3,4 ] def func ( x ) : return x**xb=sorted ( a , func ) def func2 ( x , y=4 , z=10 ) : print ( x , y , z ) func2 ( 100,200 ) -- - > output -- > > 100 200 10
why sorted ( ) in python did n't accept positional arguments ?
Python
Explain this : The expected result is of course array ( [ 0 , 1 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 ] ) .I 'm going to guess this is something to do with numpy parallelising things and not being smart enough to work out that it needs to make a temporary copy of the data first ( or do the operation in the correct order ) .I...
> > > a = np.arange ( 10 ) > > > a [ 2 : ] array ( [ 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] ) > > > a [ : -2 ] array ( [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 ] ) > > > a [ 2 : ] - a [ : -2 ] array ( [ 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 ] ) > > > a [ 2 : ] -= a [ : -2 ] > > > aarray ( [ 0 , 1 , 2 , 2 , 2 , 3 , 4 , 4 , 4 , 5 ] ) for i in r...
Weird behaviour with numpy array operations
Python
I have a program that prints out some data with ' p 's in place of decimal points , and also some other information . I was trying to replace the ' p 's with '. 's . Example output by the program : I would like to change it to : I tried using re.search to extract out the number and replace the p with . , but plugging i...
out_info = 'value is approximately 34p55 ' out_info_updated = 'value is approximately 34.55 '
Python - how to replace ' p ' in a number ( 4p5 ) with ' . ' ( 4p5- > 4.5 ) ?
Python
I happened on this peculiar behaviour accidentally : By what mechanism does calling list ( a ) unroll one level of recursion in the string representation of itself ?
> > > a = [ ] > > > a [ : ] = [ 'potato ' , a ] > > > print a [ 'potato ' , [ ... ] ] > > > print list ( a ) [ 'potato ' , [ 'potato ' , [ ... ] ] ]
Why does list ( my_list ) modify the object ?
Python
I am constructing HTML as part of a bigger project . The construction works , no issues with that . However I fear that the code is too verbose or that I am not using the full power of BeautifulSoup . For Example : I am generating a div tag of class editorial that wraps a div of class editorial-title , editorial-image ...
< div class= '' editorial '' > < div class= '' editorial-title '' > Hello < /div > < div class= '' editorial-image '' > < img src= '' https : //images.dog.ceo/breeds/collie-border/n02106166_2595.jpg '' > < /div > < div class= '' editorial-subtitle '' > world < /div > < div class= '' editorial-article '' > Yeah . But Pa...
Is there a shorter way or a pythonic way to generate custom html that follows a pattern using BeautifulSoup ?
Python
I 'm doing a homework about a heart game with different version . It says that if we are given a list mycards that contains all the cards that player currently hold in their hands . And play is a single card that representing a potential card.And if all their cards contain either HEART ( H ) or QUEEN OF SPADES ( QS ) i...
> > > mycards= [ '0H ' , '8H ' , '7H ' , '6H ' , 'AH ' , 'QS ' ] > > > play = [ 'QS ' ] if play [ 1 ] == ' H ' : return Trueif play == 'QS ' : return Trueelse : return False
How to check all the elements in a list that has a specific requirement ?
Python
I need to format the number of decimal places that a variable displays in an f-string using a variable for the number of places.Instead of value.4f , I need value.nf where n is the number of decimal places to which the variable should be rounded .
n = 5value = 0.345print ( f ' { value : .4f } ' )
Format variable in f-string with a variable number of decimal places
Python
I have an interface called IReportSettings for a registry key that has a tuple , which stores PersistantObjects that use an interface IUserSetting , which is implemented by an object type called UserSetting . A factory adaptor for IUserSetting and UserSetting is registered with registerFactoryAdapter.When I try to set ...
WrongContainedType : ( [ WrongContainedType ( [ WrongType ( 'uname ' , < type 'unicode ' > , 'user_name ' ) ] , '' ) ] , 'value ' ) class PersistentObject ( PersistentField , schema.Object ) : passclass IUserSetting ( Interface ) : user_name = schema.TextLine ( title=u '' User '' , required=True , default=u '' '' , ) f...
Plone- Why am I getting a WrongContainedType error ?
Python
I have a data set which is aggregated between two dates and I want to de-aggregate it daily by dividing total number with days between these dates.As a sampleThe data set I want is : Any help would be useful.Thanks
StoreID Date_Start Date_End Total_Number_of_sales78 12/04/2015 17/05/2015 7908980 12/04/2015 17/05/2015 79089 StoreID Date Number_Sales 78 12/04/2015 79089/38 ( as there are 38 days in between ) 78 13/04/2015 79089/38 ( as there are 38 days in between ) 78 14/04/2015 79089/38 ( as there are 38 days in between ) 78 ... ...
Python de-aggregation
Python
I need help with converting a nested list of dictionaries with a nested list of dictionaries inside of it to a dataframe . At the end , I want something that looks like ( the dots are for other columns in between ) :
id | isbn | isbn13 | ... . | average_rating| 30278752 |1594634025|9781594634024| ... . |3.92 | 34006942 |1501173219|9781501173219| ... . |4.33 | review_stat = [ { 'books ' : [ { 'id ' : 30278752 , 'isbn ' : '1594634025 ' , 'isbn13 ' : '9781594634024 ' , 'ratings_count ' : 4832 , 'reviews_count ' : 8435 , 'text_reviews_...
Nested list of dictionary with nested list of dictionary into a Pandas dataframe
Python
I 'm working on a parser for a specific type of file that is broken up into sections by some header keyword followed a bunch of heterogeneous data . Headers are always separated by blank lines . Something along the lines of the following : Every header contains very different types of data and depending on certain keyw...
Header_A1 1.023452 2.97959 ... Header_B1 5.1700 10.25002 5.0660 10.5000 ... headers = re.compile ( r '' '' '' ( ( ? P < header_a > Header_A ) | ( ? P < header_b > Header_B ) ) `` '' '' , re.VERBOSE ) i = 0while i < len ( data_lines ) : match = header.match ( data_lines [ i ] ) if match : if match.group ( 'header_a ' ) ...
Most pythonic way to break up highly branched parser
Python
I 'm trying to split strings up preceding the places where there is a whole , 2 digit number surrounded by whitespace . Eventually I 'd like this to work in Python , but I 've been workbenching with sed and I ca n't figure it out.My test data looks like this : And I would like it to be split up like this ( note the loc...
13 13 13 13 13 9:07.18 9:12.09 9:15.6514 14 14 2:04.86 2:05.99 2:06.87 14 4:21.51 4:23.51 4:25.00 14 8:56.28 9:01.09 9:04.5815 15 57.18 57.61 57.95 15 2:02.61 2:03.72 2:04.58 15 4:17.31 4:19.28 4:20.75 15 8:47.15 8:51.87 8:55.3016 16 56.34 56.76 57.09 16 2:00.69 2:01.78 2:02.63 16 4:13.75 4:15.69 4:17.14 16 8:39.71 8:4...
How can I split this string up ?
Python
longest firstshortest firstWhy is the longest first regex preferred ?
> > > p = re.compile ( 'supermanutd|supermanu|superman|superm|super ' ) > > > p = re.compile ( 'super|superm|superman|supermanu|supermanutd ' )
What is the reason behind the advice that the substrings in regex should be ordered based on length ?
Python
How do I use the ^ and $ symbols to parse only /blog/articles in the following ? I 've created ex3.txt that contains this : and the regex : does n't appear to work , as in when I type it using 'regetron ' ( see learning regex the hard way ) there is no output on the next line.This is my exact procedure : At command lin...
/blog/article/1 /blog/articles /blog /admin/blog/articles ^/blog/articles $
How to use ^ and $ to parse simple expression ?
Python
So I was testing the speeds of two versions of the same function ; one with reversing the view of a numpy array twice and one without . The code is as follows : Surprisingly , the one with an extra operation runs slightly faster on multiple occasions . I used % timeit around 10 times on both functions ; tried different...
import numpy as npfrom numba import njit @ njitdef min_getter ( arr ) : if len ( arr ) > 1 : result = np.empty ( len ( arr ) , dtype = arr.dtype ) local_min = arr [ 0 ] result [ 0 ] = local_min for i in range ( 1 , len ( arr ) ) : if arr [ i ] < local_min : local_min = arr [ i ] result [ i ] = local_min return result e...
Reversing the view of a numpy array twice in a jitted function makes the function run faster
Python
Let 's say I have an array like : and I would like to form a dictionary of the sum of the third column for each row that matches each value in the first column , i.e . return { 1 : 13 , 2 : 6 , 3 : 9 } . To make matters more challenging , there 's 1 billion rows in my array and 100k unique elements in the first column....
arr = np.array ( [ [ 1,20,5 ] , [ 1,20,8 ] , [ 3,10,4 ] , [ 2,30,6 ] , [ 3,10,5 ] ] )
Fastest way to extract dictionary of sums in numpy in 1 I/O pass
Python
I need to build a table with the data like this : I am not allowed use any Python libraries for that . It has to be done from scratch.I found that there are some box drawing unicode characters that I could use to draw the table ( https : //en.wikipedia.org/wiki/Box-drawing_character ) . Ex : I am lost on how I should a...
┌────────┬───────────┬────────┐ │ ID │ Name │ Age │ ├────────┼───────────┼────────┤ │ 1 │ Jonh │ 35 │ ├────────┼───────────┼────────┤ │ 2 │ Joseph │ 40 │ └────────┴───────────┴────────┘ print ( u'\u250C ' ) - > will print ─ length_list = [ len ( element ) for row in data for element in row ] column_width = max ( length...
Building a table with the data from scratch Python
Python
Consider the following matrix : Let say I want to subset the following arrayIt is possible with some indexing of rows and columns , for instance Then if I store the result in a variable array I can do it with the following code : Is there a way to broadcast this kind of operation ? I have to do this as a data cleaning ...
X = np.arange ( 9 ) .reshape ( 3,3 ) array ( [ [ 0 , 1 , 2 ] , [ 3 , 4 , 5 ] , [ 6 , 7 , 8 ] ] ) array ( [ [ 0 , 4 , 2 ] , [ 3 , 7 , 5 ] ] ) col= [ 0,1,2 ] row = [ [ 0,1 ] , [ 1,2 ] , [ 0,1 ] ] array=np.zeros ( [ 2,3 ] , dtype='int64 ' ) for i in range ( 3 ) : array [ : ,i ] =X [ row [ i ] , col [ i ] ]
Asymmetric slicing python
Python
I have a timeseries in Pandas where the dates are at the end of the month : When I plot this with matplotlib I get the result I 'd expect , with points at the end-of-month and the line starting just before May 2018 : But Pandas ' native plot function plots the points at the start of the month : I thought perhaps this w...
import pandas as pds = pd.Series ( { '2018-04-30 ' : 0 , '2018-05-31 ' : 1 , '2018-06-30 ' : 0 , '2018-07-31 ' : 1 , '2018-08-31 ' : 0 , '2018-09-30 ' : 1 , } ) s.index = pd.to_datetime ( s.index ) import matplotlib.pyplot as pltplt.plot ( s ) s.plot ( ) s2 = pd.Series ( [ 0.2 , 0.7 ] , index=pd.date_range ( '2018-05-0...
Pandas dates being wrongly plotted at start of month
Python
I 'm having a problem getting two subprocesses to run together . The first subprocesss is a transcode of a video stream : I need this to run in the background of my program , transcoding video from my IP camera into a mjpeg stream.The second subprocess is the Openalpr Daemon that looks at the mjpeg stream and returns c...
subprocess.Popen ( `` ffmpeg -i input output '' , shell=True ) subprocess.Popen ( `` alprd -f '' , shell=True ) import subprocesssubprocess.Popen ( `` ffmpeg -i input output '' , shell=True ) subprocess.Popen ( `` alprd -f '' , shell=True ) import subprocesssubprocess.Popen ( `` ffmpeg -i input output '' , shell=True )...
Why do two sub-processes stop each other from working ?
Python
I have a Dataframe with 1 column ( +the index ) containing lists of sublists or elements.I would like to detect common elements in the lists/sublists and group the lists with at least 1 common element in order to have only lists of elements without any common elements.The lists/sublists are currently like this ( exempl...
Num_IDRow1 [ [ 'A1 ' , 'A2 ' , 'A3 ' ] , [ 'A1 ' , 'B1 ' , 'B2 ' , 'C3 ' , 'D1 ' ] ] ` Row2 [ 'A1 ' , 'E2 ' , 'E3 ' ] Row3 [ [ 'B4 ' , 'B5 ' , 'G4 ' ] , [ 'B6 ' , 'B4 ' ] ] Row4 [ 'B4 ' , 'C9 ' ] [ 'A1 ' , 'A2 ' , 'A3 ' , 'B1 ' , 'B2 ' , 'C3 ' , 'D1 ' , 'E2 ' , 'E3 ' ] [ 'B4 ' , 'B5 ' , 'B6 ' , 'C9 ' , 'G4 ' ]
How can I detect common elements lists and groupe lists with at least 1 common element ?
Python
I have an enum.Enum subclass : and I want to be able to use < and > to see if a given member comes before or after another one in the definition order , so I could do something like this : based on where the values appear in the definitions of the enum , not the enum values themselves . I know that Enums preserve order...
class MyEnum ( Enum ) : A = `` apple '' C = `` cherry '' B = `` banana '' > > > MyEnum.A < MyEnum.BTrue > > > MyEnum.B > = MyEnum.CTrue > > > MyEnum.C < MyEnum.AFalse
How can I check ordering of items in a Python Enum ?
Python
Related : Python object conversionI recently learned that Python allows you to change an instance 's class like so : I 'm trying to figure out whether there is a case where 'transmuting ' an object like this can be useful . I 've messed around with this in IDLE , and one thing I 've noticed is that assigning a differen...
class Robe : passclass Dress : passr = Robe ( ) r.__class__ = Dress
Python : is there a use case for changing an instance 's class ?
Python
I understand the normal lambda expression , such as However , for some complex ones , I am a little confused about them . For example : Where newspaper is a function . I was wondering what actually the sets is and why the get_imdb function can return the value sets ( ) Thanks for your help ! Added : The codes are actua...
g = lambda x : x**2 for split in [ 'train ' , 'test ' ] : sets = ( lambda split=split : newspaper ( split , newspaper_devkit_path ) ) def get_imdb ( ) : return sets ( )
Confused about the lambda expression in python
Python
Consider the following code : I 'm wondering whether I could be able to do an one-liner . Obvious try is : But this solution requires list to be generated twice.Not-so-obvious try is : Which does the trick , but makes code really weird.This leads me to idea that probably there is possibility to somehow use list , gener...
a = [ ... for i in input ] i = a.index ( f ( a ) ) i = [ ... for i in input ] .index ( f ( [ ... for i in input ] ) ) i = [ a.index ( f ( a ) ) for a in [ [ ... for i in input ] , ] ] i = [ ... for i in input ] .index ( f ( _ ) ) # ori = [ ... for i in input ] .index ( f ( self ) )
Can one use list comprehension derivatives in its methods ?
Python
I am using try/except blocks as a substitute for if/elif that has a bunch of ands . I am looking into a list and replacing some elements if it has x and x and x , etc . In my project , I have to check for upwards of 6 things which drew me to using the try/except with .index ( ) which will throw an error if the element ...
colors = [ 'red ' , 'blue ' , 'yellow ' , 'orange ' ] try : red_index = colors.index ( 'red ' ) blue_index = colors.index ( 'blue ' ) colors [ red_index ] = 'pink ' colors [ blue_index ] = 'light blue'except ValueError : passtry : yellow_index = colors.index ( 'yellow ' ) purple_index = colors.index ( 'purple ' ) color...
Better way to check a list for specific elements - python
Python
I have a Django db with cooking recipes . I want to query all users who have at least 80 % ingredients to make a recipe . How do I achieve this ? Or how do I query for users who are missing only 1 ingredient for the recipe ? models.py
class ingredient ( models.Model ) : id = models.AutoField ( `` id '' , max_length = 100 , primary_key=True ) name=models.CharField ( `` Ingredient '' , max_length=100 ) def __unicode__ ( self ) : return self.nameclass user ( models.Model ) : id = models.AutoField ( `` id '' , max_length = 100 , primary_key=True ingredi...
Django manytomany field , how to get check for 80 % subset/ match ?
Python
I currently have a problem where I want to get a list of directories that are at an n-1 level . The structure looks somewhat like the diagram below , and I want a list of all the folders that are blue in color . The height of the tree however , varies across the entire file system . Due to the fact that all the folders...
def getDirList ( dir ) : dirList = [ x [ 0 ] for x in os.walk ( dir ) ] return dirListoldDirList = getDirList ( sys.argv [ 1 ] ) dirList = [ ] # Hack method for getting the foldersfor i , dir in enumerate ( oldDirList ) : if dir.endswith ( 'images ' ) : dirList.append ( oldDirList [ i ] + '/ ' )
Want to create a list of directories at the n-1 level ( folders that do not contain any subfolders ) with either bash or python
Python
I got the output but trying to find a more efficient way to do this : Output is
( df [ 'budget ' ] == 0 ) .sum ( ) , ( df [ 'revenue ' ] == 0 ) .sum ( ) , ( df [ 'budget_adj ' ] == 0 ) .sum ( ) , ( df [ 'revenue_adj ' ] == 0 ) .sum ( ) ( 5674 , 5993 , 5676 , 5993 )
Better way to check multiple columns with the same condition in pandas ?
Python
We got this 3D input_tensor which is a tensor representing ( batch_size , N , 2 ) .Where , batch_size = total batchesN = total predictions,2 = ( label , score ) I want to add the score values ( 2nd column elements ) where labels ( 1st column elements ) are same per batch . For example , given this tensor with 3 batches...
input_tensor = tf.constant ( [ [ [ 2. , 0.7 ] , [ 1. , 0.1 ] , [ 3. , 0.4 ] , [ 2. , 0.8 ] , ] , [ [ 2. , 0.7 ] , [ 1. , 0.1 ] , [ 1. , 0.4 ] , [ 4. , 0.8 ] , ] , [ [ 3. , 0.7 ] , [ 1. , 0.1 ] , [ 3. , 0.4 ] , [ 4. , 0.8 ] , ] ] ) required_output_tensor = [ [ [ 2. , 1.5 ] , [ 1. , 0.1 ] , [ 3. , 0.4 ] , ] , [ [ 2. , 0....
How to combine tensor elements with similar values of specific column ?
Python
I 've isolated the float ( ) oddity here to the object creation order , becauseNote : I 've done checks on the precision of the floats and it is not the reason why this is happening.I wish to understand why and how is Python deciding to create float objects.Why is float ( 1.0 ) pointing to the same object while float (...
float ( 1.0 ) is float ( 1.0 ) # Truefloat ( 1 ) is float ( 1 ) # False x1 = float ( 1 ) x2 = float ( 1 ) x1 is x2 # Falseid ( x1 ) == id ( x2 ) # Falsey1 = float ( 1.0 ) y2 = float ( 1.0 ) y1 is y2 # Trueid ( y1 ) == id ( y2 ) # True float ( 1 ) is float ( 1 ) # Falseid ( float ( 1 ) ) == id ( float ( 1 ) ) # Truefloa...
float ( ) object id creation order
Python
ContextI 'm trying to get all the data from this website in order to later use it in some model training project ( ML ) . I 've chosen to do it by using Scrapy + Python 3.7 . So far so good . I 've set up my Scrapy project structure and I started working on the scraper . In order to do this , I created some steps that ...
import jsonimport reimport scrapyPRODUCTS_XPATH = `` //div [ @ class='col-md-3 ' ] //a/ @ href '' class Product : def __init__ ( self , response ) : self.response = response def get_brand_name ( self ) : brand_name = self.response.xpath ( `` normalize-space ( //* [ @ class='product-brand-name-details ' ] /text ( ) ) ''...
Understanding infinite loading when using Scrapy - what 's wrong ?
Python
I 'm trying to write a function which creates dichotomously grouped list , f. ex . if my input is as following : [ a , b , c , d , e , f , g , h ] I want to choose random integer which will split it into smaller sublists again and again recursively until the sublists ' length is maximum two , like : [ [ a , [ b , c ] ]...
def split_list ( l ) : if l.__len__ ( ) > 2 : pivot = np.random.random_integers ( 0 , l.__len__ ( ) - 1 ) print ( pivot , l ) l = [ RandomTree.split_list ( l [ : pivot ] ) ] [ RandomTree.split_list ( l [ pivot : ] ) ] return l
Recursive and random grouping a list
Python
I have two dateframe ( df1 & df2 ) , i 'm trying to figure out how to use conditions from df2 to extract values from df1 and use the extracted values in df2 . df1 = values to exact fromdf2 = conditions for exaction and df where the extracted values are usedconditions : df2.HJ = df1HJ & df2.JK = df1 P columexample if df...
╔════╦════╦══════╦══════╦══════╦══════╗║ HJ ║ P1 ║ P2 ║ P3 ║ P4 ║ P5 ║╠════╬════╬══════╬══════╬══════╬══════╣║ 5 ║ 51 ║ 33 ║ 21 ║ 31 ║ 13 ║║ 11 ║ 66 ║ 45 ║ 21 ║ 49 ║ 58 ║║ 21 ║ 7 ║ 55 ║ 56 ║ 67 ║ 73 ║║ 99 ║ 0 ║ 76 ║ 67 ║ 98 ║ 29 ║║ 15 ║ 11 ║ 42 ║ 79 ║ 27 ║ 54 ║╚════╩════╩══════╩══════╩══════╩══════╝ ╔════╦════╗║ HJ ║ J...
extracting values from dataframe1 using conditions set in dataframe2 ( pandas , python )
Python
I 'm writing a piece of code that returns profiling information and it would be helpful to be able to dynamically return the implementation of Python in use.Is there a Pythonic way to determine which implementation ( e.g . Jython , PyPy ) of Python my code is executing on at runtime ? I know that I am able to get versi...
> > > import sys > > > sys.version ' 3.4.3 ( default , May 1 2015 , 19:14:18 ) \n [ GCC 4.2.1 Compatible Apple LLVM 6.1.0 ( clang-602.0.49 ) ] '
Determining implementation of Python at runtime ?
Python
I noticed that something weird happens when I use a recursion inside a list comprehension . If the recursion goes too deep the interpreter seemingly goes idle ( I waited for 5 minutes and nothing happened ) .For the sake of this question assume that I want to flatten nested lists ( I do n't - but it 's a short code sam...
def flatten ( x ) : if isinstance ( x , list ) : return [ a for i in x for a in flatten ( i ) ] else : return [ x ] def wrap_in_lists ( value , depth ) : a = value for _ in range ( depth ) : a = [ a ] return a > > > flatten ( wrap_in_lists ( 1 , 2**10 ) ) [ 1 ] > > > flatten ( wrap_in_lists ( 1 , 2**11 ) ) # Nothing ha...
What is special about a recursive call in a comprehension when the recursion goes very deep ?