lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Python
I am attempting to utilize the Presenter-First approach to a new project . I find myself with unittest below . Am I utilizing poor unit testing practices by including so many assertions in this test ? If yes , is the issue with my approach to the test or to the implementation of presenter.setOverview ? In otherwords , ...
def testSetOverview ( self ) : # set up mock objects p = PropertyMock ( ) type ( self.mock_model ) .descriptions = p self.mock_model.getData.side_effect = [ 5 , 10 ] self.mock_model.getDescription.side_effect = 'Description ' # get required variables end = dt.date.today ( ) start = dt.date ( year=end.year , month=1 , d...
Presenter-First Unittest with Multiple Assertions
Python
I have a dictionary surnames : I would like to sum all arrays and save them in the same dictionary so that the sum replaces the array : I tried this : I assume this does n't work because it only sums single values of the same key ? I also tried this : I understand why this does n't work either , but what else can I do ...
import numpy as npsurnames = { 'Sophie ' : np.array ( [ 138 , 123 ] ) , 'Marie ' : np.array ( [ 126 , 1 , 50 , 1 ] ) , 'Maximilian ' : np.array ( [ 111 , 74 ] ) , 'Alexander ' : 87 , 'Maria ' : np.array ( [ 85 , 15 , 89 , 2 ] ) , 'Paul ' : np.array ( [ 70 , 59 ] ) , 'Katharina ' : 69 , 'Felix ' : np.array ( [ 61 , 53 ]...
Replace values in a dictionary of NumPy arrays and single numbers with sums
Python
Consider the numpy.array iExample 1index Example 2columnsButLeads to this when I display itHowever , df.T works ! ? QuestionWhy is it necessary for index values to be hashable in a column context but not in an index context ? And why only when it 's displayed ?
i = np.empty ( ( 1 , ) , dtype=object ) i [ 0 ] = [ 1 , 2 ] iarray ( [ list ( [ 1 , 2 ] ) ] , dtype=object ) df = pd.DataFrame ( [ 1 ] , index=i ) df 0 [ 1 , 2 ] 1 df = pd.DataFrame ( [ 1 ] , columns=i ) df TypeError : unhashable type : 'list '
Why is it ok to have an index with lists as values but not ok for columns ?
Python
When using Decimal ( 0 ) and formatting it to .2e format the following happens : However if you just use 0 or 0. the following happens : How come the results are different ?
> > > f ' { Decimal ( 0 ) : .2E } '' 0.00E+2 ' > > > f ' { 0. : .2E } '' 0.00E+00 '
Why is the scientific formatting of Decimal ( 0 ) different from float 0 ?
Python
I tend to get a LOT of IndentationErrors when writing python code . Sometimes the error will go away when I delete and rewrite the line . Can someone provide a high level explanation of IndentationErrors in python for noob ? Here is an example of a recent indentationError I received while playing CheckIO that will not ...
def checkpass ( data ) : `` '' '' Checks password for > =10 char + 1 number + 1 LC letter + 1 UC letter '' '' '' passlist = [ ] uclist = [ ' A ' , ' B ' , ' C ' , 'D ' , ' E ' , ' F ' , ' G ' , ' H ' , ' I ' , ' J ' , ' K ' , ' L ' , 'M ' , ' N ' , ' O ' , ' P ' , ' Q ' , ' R ' , 'S ' , 'T ' , ' U ' , ' V ' , ' W ' , '...
Understanding IndentationErrors in Python 2.7
Python
I 'm trying to add float values of a vector according to integer values from another vector . for instance if I have : I would like to add the 5 first value of the a vector together ( because the 5 first values of b are 0 ) , the 3 next values together ( because the 3 next values of b are 1 ) and so on.So At the end I ...
import numpy as npa = np.array ( [ 0.1,0.2,0.3,0.4,0.5,0.6,07.3,0.8,0.9,1.,1.2,1.4 ] ) b = np.array ( [ 0,0,0,0,0,1,1,1,2,2,2,2 ] ) .astype ( int ) c = function ( a , b ) c = [ 0.1+0.2+0.3+0.4+0.5 , 0.6+7.3+0.8 , 0.9+1.+1.2+1.4 ]
Is it possible to combine ( add ) values of a vector according to integer value of another vector
Python
I have a Panda 's dataframe like the following : And i want to get the countries where its PIB in 2007 was less than in 2002 , but i couldn´t code something to do that only using Pandas built in methods without use python iterations or something like that.The most i 've got is the following line : But i get the followi...
df [ df [ df.year == 2007 ] .PIB < df [ df.year == 2002 ] .PIB ] .country ValueError : Can only compare identically-labeled Series objects
How to compare data from the same column in a dataframe ( Pandas )
Python
Apologies if the question title is too vague - would welcome edits.I 'm trying to parse XML using BeautifulSoup , but because each function call could return None , I have to parse a single element over a number of lines . This gets unwieldy very quickly : Doing the same thing in Swift , a language I 'm far more famili...
books_count = result.books_countif not books_count : return Nonebooks_count = books_count.stringif not books_count : return Nonebooks_count = int ( books_count ) if not books_count : return None guard let booksCountString = result.booksCount ? .string , let booksCountInt = Int ( booksCountString ) else { return nil }
How can I make string parsing in Python less unwieldy ?
Python
I 'm working with someone 's Java code where a key data structure is a m x n x p array , float [ ] [ ] [ ] . I need to get it into Python ; currently my approach is to save the array to a text file using Arrays.deepToString and then parse that text file from Python.I am stuck on how to write a regular expression that w...
float_pat = r'\d\.\d* ( ? : E-\d+ ) ? ' list_of_floats_pat = r'\ [ ( ? : \d\.\d* ( ? : E-\d+ ) ? ) , ) +\ ] ' [ [ [ 0.6453525160688715 , 0.15620941152962334 , 0.1874313118193626 , 9.991008092716556E-5 , 9.991008092716556E-5 , 9.991008092716556E-5 , 9.991008092716556E-5 , 0.01050721017750691 , 9.991008092716556E-5 ] , [...
Use Python regex to parse string of floats output by Java Arrays.deepToString
Python
From my understanding , if a variable of an immutable type is assigned a value equal to another variable of the same immutable type , they should both be referencing the same object . I am using Python 2.7.6 , do n't know if this is a bug.This behaves like I how understood : However , by altering a character , this doe...
x = 'ab ' y = 'ab'id ( x ) == id ( y ) True x = ' a # ' y = ' a # 'id ( x ) == id ( y ) False x , y = ' a # ' , ' a # 'id ( x ) == id ( y ) True
Why is there strange behavior between the IDs of equivalent strings ?
Python
I am retrieving some content from a website which has several tables with the same number of columns , with pandas read_html . When I read a single link that actually has several tables with the same number of columns , pandas effectively read all the tables as one ( something like a flat/normalized table ) . However ,...
import multiprocessingdef process ( url ) : df_url = pd.read_html ( url ) df = pd.concat ( df_url , ignore_index=False ) return df_urllinks = [ 'link1.com ' , 'link2.com ' , 'link3.com ' , ... , 'linkN.com ' ] pool = multiprocessing.Pool ( processes=6 ) df = pool.map ( process , links ) df [ [ Form Disponibility \ 0 29...
How to reindex malformed columns retrived from pandas read_html ?
Python
When I 'm trying to check whether a list is empty or not using python 's not operator it is behaving in a weird manner.I tried using the not operator with a list to check whether it is empty or not.The expected output for not ( a ) == False should be False .
> > > a = [ ] > > > not ( a ) True > > > not ( a ) == TrueTrue > > > not ( a ) == FalseTrue > > > True == FalseFalse
Weird behaviour of ` not ` operator with python list
Python
I have a python script that is reading slices from a 3D array , like this : I ca n't help but think there must be a better way of doing this ! Any suggestions ? S
def get_from_array ( axis , start , end , array ) : if axis == 0 : slice = array [ start : end , : , : ] elif axis == 1 : slice = array [ : , start : end , : ] elif axis == 2 : slice = array [ : , : , start : end ] return slice
Python - how can I address an array along a given axis ?
Python
Please explain below , I think it should have printed True or False since these are boolean expressions . And why it 's printing 2 1 and then 1 2 output :
print 1 and 2print 2 and 1print 1 or 2print 2 or 1 2112
Quirky output python
Python
I am trying to use mypy to check a Python 3 project . In the example below , I want mypy to flag the construction of the class MyClass as an error , but it doesn't.Can anyone explain this , please ? I.e . explain why mypy does not report an error ?
class MyClass : def __init__ ( self , i : int ) - > None : passobj = MyClass ( False )
Mypy does n't throw an error when mixing booleans with integers
Python
We know that tuple objects are immutable and thus hashable . We also know that lists are mutable and non-hashable . This can be easily illustrated Now , what is the meaning of hash in this context , if , in order to check for uniqueness ( e.g . when building a set ) , we still have to check each individual item in what...
> > > set ( [ 1 , 2 , 3 , ( 4 , 2 ) , ( 2 , 4 ) ] ) { ( 2 , 4 ) , ( 4 , 2 ) , 1 , 2 , 3 } > > > set ( [ 1 , 2 , 3 , [ 4 , 2 ] , [ 2 , 4 ] ] ) TypeError : unhashable type : 'list '
What is the meaning of hash if we still need to check every item ?
Python
I have such a list with alphanumeric items : I 'm trying to sort it in such an order , using sorted method : but what I get is : I tried passing several keys to sorted , but I ca n't quite figure it out . What key should I use ? Or should I use another method ?
[ 'A08 ' , 'A09 ' , 'A02 ' , 'A03 ' , 'A06 ' , 'A07 ' , 'A04 ' , 'A05 ' , 'A15 ' , 'A14 ' , 'A17 ' , 'A16 ' , 'A11 ' , 'B01 ' , 'B03 ' , 'B02 ' , 'B05 ' , 'B04 ' , 'B07 ' , 'B06 ' , 'B09 ' , 'B08 ' , 'B16 ' , 'B17 ' , 'B14 ' , 'B15 ' , 'C05 ' , 'C06 ' , 'C07 ' , 'C19 ' , 'C13 ' , 'C12 ' , 'C11 ' , 'C10 ' , 'C17 ' , 'C1...
Sort list with alphanumeric items by letter first
Python
The answer to Javascript regex question Return the part of the regex that matched is `` No , because compilation destroys the relationship between the regex text and the matching logic . `` But Python preserves Match Objects , and re.groups ( ) returns the specific group ( s ) that triggered a match . It should be simp...
import repat = `` ( ^\d+ $ ) | ( ^\w+ $ ) | ( ^\W+ $ ) '' test = [ ' a ' , 'c3 ' , '36d ' , '51 ' , '29.5 ' , ' # $ % & ' ] for t in test : m = re.search ( pat , t ) s = ( m.lastindex , m.groups ( ) ) if m else `` print ( str ( bool ( m ) ) , s ) True ( 2 , ( None , ' a ' , None ) ) True ( 2 , ( None , 'c3 ' , None ) )...
How to return the regex that matches some text ?
Python
I 'm using Python 3.8.3 & I got some unexpected output like below when checking id of strings.After the line which adding `` h '' to a , id ( a ) did n't change . How is that possible when strings are immutable ? I got this same output when I use a=a+ '' h '' instead of a+= '' h '' and run this code in a .py file also ...
> > > a= '' d '' > > > id ( a ) 1984988052656 > > > a+= '' e '' > > > id ( a ) 1985027888368 > > > a+= '' h '' > > > id ( a ) 1985027888368 > > > a+= '' i '' > > > id ( a ) 1985027888368 > > >
Confused why after 2nd evaluation of += operator of immutable string does not change the id in Python3
Python
I have a test dataframe : Output : When I call stack on this dataframe , I get this result : Output : How can I prevent stack from sorting the indices so that the order of Group2 remains as A , B , C , All ?
df1 = pd.DataFrame ( { `` Group1 '' : [ `` X '' , `` Y '' , `` Y '' , `` X '' , `` Y '' , `` Z '' , `` X '' , `` Y '' ] , `` Group2 '' : [ `` A '' , `` C '' , `` A '' , `` B '' , `` C '' , `` C '' , `` B '' , `` A '' ] , `` Number1 '' : [ 1 , 3 , 5 , 1 , 5 , 2 , 5 , 3 ] , `` Number2 '' : [ 6 , 2 , 6 , 2 , 7 , 2 , 6 , 8...
How can I prevent stack from sorting indices ?
Python
I currently have a code that searches for files by keyword . Is there a way to show the number of files found , as the code runs and or show the progress ? I have a large directory to search and would like to see the progress if possible . The code I currently have does n't show much info or processing time .
import osimport shutilimport timeimport sysdef update_progress_bar ( ) : print '\b . ' , sys.stdout.flush ( ) print 'Starting ' , sys.stdout.flush ( ) path = '//server/users/'keyword = 'monthly report'for root , dirs , files in os.walk ( path ) : for name in files : if keyword in name.lower ( ) : time.sleep ( 0 ) updat...
Display number of files found and progress
Python
I 'm quiet confused to get this with python as below I guess the reason is that in variable a , all three lists ponit to the same memory area until they are used in different ways . Is it right ? Should I always be careful when doing initialization using things like * operator ? THANKS !
> > > a = [ [ ] ] *3 > > > c= [ [ ] , [ ] , [ ] ] > > > a [ [ ] , [ ] , [ ] ] > > > c [ [ ] , [ ] , [ ] ] > > > a == cTrue > > > a [ 1 ] .append ( 2 ) > > > a [ [ 2 ] , [ 2 ] , [ 2 ] ] > > > c [ 1 ] .append ( 2 ) > > > c [ [ ] , [ 2 ] , [ ] ]
interesting thing about python list initializing
Python
I have an N-by-2 array of N 2D points , which I want to assign to an M-by-K grid of bins.For instance , points [ m + 0.1 , k ] and [ m + 0.1 , k + 0.9 ] should fall into bin [ m , k ] , where both m and k are integers . It 's possible that a point does n't fall into any of the bins.Implementation-wise , I want the resu...
M = 10K = 11N = 100pts = 20 * np.random.rand ( N , 2 ) in_bin = np.zeros ( ( M , K , N ) , dtype=bool ) for m in range ( M ) : for k in range ( K ) : inbin_h = ( pts [ : , 0 ] > = m ) & ( pts [ : , 0 ] < ( m + 1 ) ) inbin_w = ( pts [ : , 1 ] > = k ) & ( pts [ : , 1 ] < ( k + 1 ) ) in_bin [ m , k , np.where ( inbin_h & ...
Python : Faster or Loop-Free Way of Assigning Points to Bins ?
Python
I am relatively new to python , so I will try my best to explain what I am trying to do . I am trying to iterate through two lists of stars ( which both contain record arrays ) , trying to match stars by their coordinates with a tolerance ( in this case Ra and Dec , which are both indices within the record arrays ) . H...
from __future__ import print_functionimport numpy as np # # # importing data # # # Astars = list ( ) for s in ApStars : # # # this is imported but not shown Astars.append ( s ) wStars = list ( ) data1 = np.genfromtxt ( '6819.txt ' , dtype=None , delimiter= ' , ' , names=True ) for star in data1 : wStars.append ( star )...
Preventing multiple matches in list iteration
Python
I need a web socket client server exchange between Python and JavaScript on an air-gapped network , so I 'm limited to what I can read and type up ( believe me I 'd love to be able to run pip install websockets ) . Here 's a bare-bones RFC 6455 WebSocket client-server relationship between Python and JavaScript . Below ...
< script > const message = { name : `` ping '' , data : 0 } const socket = new WebSocket ( `` ws : //localhost:8000 '' ) socket.addEventListener ( `` open '' , ( event ) = > { console.log ( `` socket connected to server '' ) socket.send ( JSON.stringify ( message ) ) } ) socket.addEventListener ( `` message '' , ( even...
Why does client.recv ( 1024 ) return an empty byte literal in this bare-bones WebSocket Server implementation ?
Python
Let 's assume we have the following dataframe that includes customer orders ( order_id ) and the products that the individual order contained ( product_id ) : It would be interesting to know how often product pairs appeared together in the same basket.How does one create a co-occurence matrix in python that looks like ...
import pandas as pddf = pd.DataFrame ( { 'order_id ' : [ 1 , 1 , 1 , 1 , 2 , 2 , 2 , 3 , 3 , 3 , 3 ] , 'product_id ' : [ 365 , 48750 , 3333 , 9877 , 48750 , 32001 , 3333 , 3333 , 365 , 11202 , 365 ] } ) print ( df ) order_id product_id0 1 3651 1 487502 1 33333 1 98774 2 487505 2 320016 2 33337 3 33338 3 3659 3 1120210 ...
How to create a co-occurence matrix of product orders in python ?
Python
Given a dataframe df , ( real life is a +1000 row df ) . Elements of ColB are lists of lists.How can efficiently create a ColC that is a string using the elements in the different columns , like this : I tried with df.apply along these lines , inspired by this : This works for the first 2 elements of the string . Havin...
ColA ColB0 ' A ' [ [ ' a ' , ' b ' , ' c ' ] , [ 'd ' , ' e ' , ' f ' ] ] 1 ' B ' [ [ ' f ' , ' g ' , ' h ' ] , [ ' i ' , ' j ' , ' k ' ] ] 2 ' A ' [ [ ' l ' , 'm ' , ' n ' ] , [ ' o ' , ' p ' , ' q ' ] ] ColC ' A > +a b : c , +d e : f '' B > +f g : h , +i j : k '' A > +l m : n , +o p : q ' df [ 'ColC ' ] = df.apply ( ...
How to create strings from dataframe columns elements in Python ?
Python
ProblemI need to reduce the length of a DataFrame to some externally defined integer ( could be two rows , 10,000 rows , etc. , but will always be a reduction in overall length ) , but I also want to keep the resulting DataFrame representative of the original . The original DataFrame ( we 'll call it df ) has a datetim...
# Define the desired final length.final_length = 2 # Define the first timestamp.first_timestamp = df [ 'utc_time ' ] .min ( ) .timestamp ( ) # Define the last timestamp.last_timestamp = df [ 'utc_time ' ] .max ( ) .timestamp ( ) # Define the difference in seconds between the first and last timestamps.delta_t = last_tim...
Unexpected number of bins in Pandas DataFrame resample
Python
I need to check if a point lies inside a bounding cuboid . The number of cuboids is very large ( ~4M ) . The code I come up with is : It takes 8 seconds to run np.all and 3 seconds to run np.nonzero on my computer . Any idea to speed up the code ?
import numpy as np # set the numbers of points and cuboidsn_points = 64n_cuboid = 4000000 # generate the test datapoints = np.random.rand ( 1 , 3 , n_points ) *512cuboid_min = np.random.rand ( n_cuboid , 3 , 1 ) *512cuboid_max = cuboid_min + np.random.rand ( n_cuboid , 3 , 1 ) *8 # main body : check if the points are i...
How to speed up numpy.all and numpy.nonzero ( ) ?
Python
I am working with a pandas dataframe . I am trying to split a column after the date and time from the rest of the string.Desired output : If I try something like df [ `` data '' ] .str.extract ( '^ ( .* ? [ 0-9 ] { 2 } ) ( . * ) $ ' ) it just strips everything after the 22 ( day )
df data0 Oct 22 12:56:52 server11 Oct 22 12:56:52 server22 Oct 22 12:56:53 server23 Oct 22 12:56:54 server24 Oct 22 12:56:56 comp2 df date machine0 Oct 22 12:56:52 server11 Oct 22 12:56:52 server22 Oct 22 12:56:53 server23 Oct 22 12:56:54 server24 Oct 22 12:56:56 comp2
Pandas split after month day time from rest of string
Python
I have 2 lists which i have created and added an incrementing value to each item . The reason being that the values in each list are to be joined together in a dictionary . However the values in each list are not a 1 to 1 pair..this is why i added the incrementing values to assist with associating each key with it 's c...
list_a = [ 'abc|1 ' , 'bcd|2 ' , 'cde|3 ' ] list_b = [ '1234|1 ' , '2345|2 ' , '3456|2 ' , '4567|2 ' , '5678|3 ' ] my_dict = { 'abc|1 ' : '1234|1 ' , 'bcd|2 ' : [ '2345|2 ' , '3456|2 ' , '4567|2 ' ] , 'cde|3 ' : '5678|3 ' }
Python- add to dictionary based on an incrementing value in 2 lists
Python
Simple question : So it seems that if I assign a dictionary literal with a duplicate key to a variable it is the second key/pair that is used , at least for this particular python version.Is this behaviour guaranteed ?
Python 2.6.6 ( r266:84292 , Aug 9 2016 , 06:11:56 ) [ GCC 4.4.7 20120313 ( Red Hat 4.4.7-17 ) ] on linux2Type `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > d = { 'foo':1 , 'foo':2 } > > > print d { 'foo ' : 2 } > > > d = { 'foo':2 , 'foo':1 } > > > print d { 'foo ' : 1 }
Assigning python dictionary literals : are the semantics guaranteed ?
Python
I have the following code in Python:1.For times = 1000000 I get the results : generator : 0.107323884964list : 0.2254931926732.For times = 10000000 I get : generator : 0.856524944305list : 1.83883309364I understand why the 2nd list would take more time to create but why would the 2nd generator take more time as well ? ...
import timeimport sysdef returnlist ( times ) : t = time.time ( ) l = [ i for i in range ( times ) ] print `` list : { } '' .format ( time.time ( ) - t ) return ldef returngenerator ( times ) : t = time.time ( ) g = ( i for i in range ( times ) ) print `` generator : { } '' .format ( time.time ( ) - t ) return gg = ret...
Python Generator that yields more results takes more time to create
Python
I am going through this link to understand Multi-channel CNN Model for Text Classification.The code is based on this tutorial.I have understood most of the things , however I ca n't understand how Keras defines the output shapes of certain layers.Here is the code : define a model with three input channels for processin...
# Skipped keras imports # load a clean datasetdef load_dataset ( filename ) : return load ( open ( filename , 'rb ' ) ) # fit a tokenizerdef create_tokenizer ( lines ) : tokenizer = Tokenizer ( ) tokenizer.fit_on_texts ( lines ) return tokenizer # calculate the maximum document lengthdef max_length ( lines ) : return m...
Understanding shapes of Keras layers
Python
I want to count the number of duplicated tuples in a list.For example num_list:I want to return the result : Total duplicates : 1which is the ( 2 , 8 ) pair.what i have so far is not very efficient , so I am wondering if there 's a more efficient way to do this ?
num_list = [ ( 3,14 ) , ( 2,8 ) , ( 10,25 ) , ( 5,17 ) , ( 3,2 ) , ( 7,25 ) , ( 4,30 ) , ( 8,7 ) , ( int ( 2 ) ,8 ) , ( 1,22 ) ] count = 0for a in num_list : for b in num_list : if a is b : continue if a [ 0 ] == b [ 0 ] and a [ 1 ] == b [ 1 ] : count += 1
Count the number of duplicate tuples inside a list
Python
I have a and the Output should be `` five '' is the first element because in list1 has the highest number of occurrences ( 3 ) '' two '' is the second element because in list1 has the next highest number of occurrences ( 2 ) '' one '' , `` three '' and `` six '' have the same lower number of occurrences ( 1 ) so they a...
list1 = [ `` one '' , `` two '' , `` two '' , `` three '' , `` four '' , `` five '' , `` five '' , `` five '' , `` six '' ] list2 = [ `` five '' , `` two '' , `` one '' , `` three '' , `` six '' ] my_dict = { i : list1.count ( i ) for i in list1 }
How to sort a list with duplicate items by the biggest number of duplicate occurrences - Python
Python
I came up with this Python code for the trial division variant of the `` Sieve of Eratosthenes '' : It does n't work as I expected.When debugging it I get some behavior I do n't understand when filter gets called : the x parameter of the lambda gets a concrete argument which is the next element from the picker generato...
import itertoolsdef sieve ( ) : # begin with all natural numbers above 1 picker = itertools.count ( 2 ) while True : # take the next available number v = next ( picker ) yield v # filter from the generator its multiples picker = filter ( lambda x : x % v ! = 0 , picker ) s = sieve ( ) for i in range ( 5 ) : print ( nex...
Troublesome filter behavior when implementing the `` Sieve of Eratosthenes '' in python
Python
I 've spent the last 2 hours on this and I 've probably read every question on here relating to variables being passed to functions . My issue is the common one of the parameter/argument being affected by changes made inside the function , even though I have removed the reference/alias by using variable_cloned = variab...
def add_column ( m ) : # this should `` clone '' m without passing any reference on m_cloned = m [ : ] for index , element in enumerate ( m_cloned ) : # parameter m can be seen changing along with m_cloned even # though 'm ' is not touched during this function except to # pass it 's contents onto 'm_cloned ' print `` T...
Passed argument/parameter in function is still being changed after removing the reference/alias
Python
I want to add a new column , Category , in each of my 8 similar dataframes.The values in this column are the same , they are also the df name , like df1_p8 in this example.I have used : Ultimately , I want to append/concat these 8 dataframes into one dataframe.I wonder if there is more efficient way to do it , rather t...
In : df61_p8.insert ( 3 , '' Category '' , '' df61_p8 '' , True ) # or simply , df61_p8 [ 'Category ' ] ='df61_p8'Out : code violation_description Category89491 9-1-503 Defective or obstructed duct system one- building df61_p8102045 9-1-503 Defective or obstructed duct system one- building df61_p8103369 9-1-503 Defecti...
More efficient way to add columns with same string values in multiple dataframes with loops or lambdas ?
Python
I 'm trying to link multiple rows from a DataFrame in order to get all possible paths formed by connecting receiver ids to sender ids.Here is an example of my DataFrame : created with : Result of my code should be list of chained ids and the total amount for the transaction chain . For the first two rows in the above e...
transaction_id sender_id receiver_id amount0 213234 002 125 101 223322 017 354 902 343443 125 689 703 324433 689 233 54 328909 354 456 10 df = pd.DataFrame ( { 'transaction_id ' : { 0 : '213234 ' , 1 : '223322 ' , 2 : '343443 ' , 3 : '324433 ' , 4 : '328909 ' } , 'sender_id ' : { 0 : '002 ' , 1 : '017 ' , 2 : '125 ' , ...
Summing a transaction chain in a dataframe , rows linked by column values
Python
I would like to create a game in python but I need a thought provoking impulse , how I can draw a point , which draws a line behind him/a trail , so far , so good , I have no idea how to make my point not just moving in the 4 directions , I want him to move forward on his own and the user should steer left and right.Mi...
import pygameimport ospygame.init ( ) width , height = 970 , 970screen = pygame.display.set_mode ( ( width , height ) ) h_center = ( ( height / 2 ) - 4 ) w_center = ( ( width / 2 ) - 4 ) class Point ( pygame.sprite.Sprite ) : def __init__ ( self ) : self.image = pygame.image.load ( os.path.join ( `` assets '' , `` poin...
Python point curves
Python
So , lets say I have this code : As seen in the comment , if the print statement is uncommented , the code works normally , and the signal handler will catch any subsequent CTRL-C presses like it should . However , if left commented , another signal will never be caught.Why is this ? My guess is that consecutive sleep ...
import signalfrom time import sleepdef signalHandler ( sig , frame ) : print `` signalHandler '' while True : sleep ( 1 ) # print `` Caught '' # Uncomment this line , and you get multiple signals - commented , you don't.signal.signal ( signal.SIGINT , signalHandler ) while True : sleep ( 1 )
python - Catching signals between sleep calls
Python
I was recently surprised to find that the `` splat '' ( unary * ) operator always captures slices as a list during item unpacking , even when the sequence being unpacked has another type : Compare to how this assignment would be written without unpacking : It is also inconsistent with how the splat operator behaves in ...
> > > x , *y , z = tuple ( range ( 5 ) ) > > > y [ 1 , 2 , 3 ] # list , was expecting tuple > > > my_tuple = tuple ( range ( 5 ) ) > > > x = my_tuple [ 0 ] > > > y = my_tuple [ 1 : -1 ] > > > z = my_tuple [ -1 ] > > > y ( 1 , 2 , 3 ) > > > def f ( *args ) : ... return args , type ( args ) ... > > > f ( ) ( ( ) , < clas...
Is there a way to splat-assign as tuple instead of list when unpacking ?
Python
I am making a little wrapper module for a public library , the library has a lot of repetition , where after object creation , maybe methods require the same data elements . I have to pass the same data in my wrapper class , but do n't really want to pass the same thing over and over . So I would like to store the data...
class Stackoverflow ( ) : def __init__ ( self , **kwargs ) : self.gen_args = { } # Optionally add the repeated element to the object if 'index ' in kwargs : self.gen_args [ 'index ' ] = kwargs [ 'index ' ] if 'doc_type ' in kwargs : self.gen_args [ 'doc_type ' ] = kwargs [ 'doc_type ' ] # This is where the problem is d...
decorating a method in python
Python
I defined the following Enum in Python : I would expect thatwill returnHowever , what I get is quite confusingWhy is it so ?
class Unit ( Enum ) : GRAM = ( `` g '' ) KILOGRAM = ( `` kg '' , GRAM , 1000.0 ) def __init__ ( self , symbol , base_unit = None , multiplier = 1.0 ) : self.symbol = symbol self.multiplier = multiplier self.base_unit = self if base_unit is None else base_unit print ( Unit.GRAM.base_unit ) print ( Unit.KILOGRAM.base_uni...
Referring Enum members to each other
Python
I am trying to turn information on a picture of 13 colourful blocks into some texts . For example , I need to know how many yellow and blue blocks here , and their sequence . `` c : \target.jpg '' `` c : \blue.jpg '' '' c : \yellow.jpg '' What I have is : When I run them separately , it gives results like these : andWe...
import cv2import numpy as npimg_rgb = cv2.imread ( `` c : \\target.jpg '' ) img_gray = cv2.cvtColor ( img_rgb , cv2.COLOR_BGR2GRAY ) template = cv2.imread ( ' c : \\blue.jpg',0 ) # template = cv2.imread ( ' c : \\blue.jpg',0 ) w , h = template.shape [ : :-1 ] res = cv2.matchTemplate ( img_gray , template , cv2.TM_CCOEF...
Arranging sequences in 2 combined arrays using Python
Python
I am trying to do the following logic in a join_key . date + book + bdr + COALECSE ( cusip , isin , deal , id ) I am trying to use : Also tried : For some reason this code isnt picking up Id as part of the key.For example in the 2nd row I should get 20191031|15|ITOR|8011898573.Also if it helps it comes from a csv where...
+ -- -- -- -- -- -- + -- -- -- + -- -- -- + -- -- -- -- -- -+ -- -- -- -- -- -- -- + -- -- -- + -- -- -- -- -- -- + -- -- -- -- -- -- -- -- -- -- -- -- -- -- +| endOfDay | book | bdr | cusip | isin | Deal | Id | join_key |+ -- -- -- -- -- -- + -- -- -- + -- -- -- + -- -- -- -- -- -+ -- -- -- -- -- -- -- + -- -- -- + --...
Pandas , fillna/bfill to concat and coalesce fields
Python
I am trying to make a word guessing game . Everything works except for the last if statement part . If the user guesses the name correctly , it does n't print `` Won ! '' . However , if not , else statement executes and it does print `` Lost ! '' . Why is that ? I checked it many times , but I coulnd't find any error.N...
import randomdef get_random_word ( ) : words = [ `` Ronnie '' , `` Deskty '' , `` Lorrie '' ] word = words [ random.randint ( 0 , len ( words ) -1 ) ] return worddef show_word ( word ) : for character in word : print ( character , `` `` , end= '' '' ) print ( `` '' ) def get_guess ( ) : print ( `` Enter a letter : `` )...
Why does n't this if statement execute ?
Python
I am trying to write a blackjack code in python 2.7 and ca n't figure out how to sum my c1 and c2 once an output is given . This is what I have so far : output : *The current syntax return the wrong sum is being calculated . The sum should be 16 . Could someone please provide guidance ? Thank you
def blackjackTips ( c1 , c2 ) : print `` Welcome to Blackjack ! '' print `` Your cards are '' , name [ c1-1 ] , '' & '' , name [ c2-1 ] total= sum ( [ c1 ] + [ c2 ] ) print `` Your card total is '' , totalname = ( ' A ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' , ' 6 ' , ' 7 ' , ' 8 ' , ' 9 ' , '10 ' , ' J ' , ' Q ' , ' K ' ) va...
summing string and integers in list in python
Python
I am just starting to play with OpenCV and I have found some very strange behaviour from the contourArea function.See this image.It has three non connected areas , the left is a grouping of long strokes and on the top center there is a single dot and finally a big square on the right.When I run my function , I get this...
Contour [ 0 ] Area : 221 , Length : 70 , Colour : Red Contour [ 1 ] Area : 13772 , Length : 480 , Colour : Green Contour [ 2 ] Area : 150 , Length : 2370 , Colour : Blue Square Areawidth = 118height = 116118 * 116 = 13,688 Dot Areawidth = 27height = 6 27*6 = 162 Contour [ 0 ] Area : 1805 , Length : 423 , Colour : Red C...
Open CV Contour area miscalculation
Python
I have a NumPy r by c matrix of zeroes and ones . And I have a list of c words . I want to return a list of length r where each element is a space delimited string made up of only those words that match 1 's in that matrix 's row . Here 's an example : What is a Pythonic way to accomplish this ? Thanks , G
matrix=np.array ( [ [ 0,0,1 ] , [ 1,0,1 ] , [ 0,1,1 ] ] ) words= [ 'python ' , ' c++ ' , '.net ' ] output= [ ] for row in range ( matrix.shape [ 0 ] ) : output.append ( ' '.join ( [ words [ i ] for i in range ( matrix.shape [ 1 ] ) if matrix [ row , i ] ==1 ] ) )
From matrix to list of words
Python
I 'm learning numpy . But I got some questions confused me : and : sum ( a ) give the same result.So why a built-in function can support the calculation of a data type from a third-party library ? min ( ) and max ( ) do the same . ( When the dim is 1 ) I got two guesses about this , I prefer the latter : python core de...
> > > import numpy as np > > > a = np.arange ( 10 ) > > > a.sum ( ) 45
Why python bulit-in functions such as sum ( ) , max ( ) , min ( ) can be used to calculate the numpy 's datatype ndarray ?
Python
I have data in following format : I would like to fill data in second column to match row that has same first column and non null value in second . So I would get following : How can it be achieved ?
8A564 nan json8A928 nan json8A563 nan json8A564 10616280 json8A563 10616222 json8A564 nan json8B1BB 10982483 json8A564 10616280 json 8A564 10616280 json8A928 nan json8A563 10616222 json8A564 10616280 json8A563 10616222 json8A564 10616280 json8B1BB 10982483 json8A564 10616280 json
Filling cell based on existing cells
Python
I , a beginner , am working on a simple card-based GUI . written in Python . There is a base class that , among other things , consists a vocabulary of all the cards , like _cards = { 'card1_ID ' : card1 , 'card2_ID ' : card2 } . The cards on the GUI are referenced by their unique IDs . As I plan to make the code avabi...
def shift ( self , card_ID , amount ) : `` '' '' Moves the card by the given amount of pixels . : param amount : the horizontal and vertical amount of shifting in pixels ; tuple '' '' '' try : self._cards [ card_ID ] .shift ( amount ) except KeyError : raise ValueError ( `` Invaild card ID '' ) def align ( self , card_...
Catching the same expection in every method of a class
Python
I have a voting dataset like that : but they are both string so I want to change them to integer matrix and make statistichou_dat = pd.read_csv ( `` house.data '' , header=None ) however , it shows error , how to solve it ? :
republican , n , y , n , y , y , y , n , n , n , y , ? , y , y , y , n , yrepublican , n , y , n , y , y , y , n , n , n , n , n , y , y , y , n , ? democrat , ? , y , y , ? , y , y , n , n , n , n , y , n , y , y , n , ndemocrat , n , y , y , n , ? , y , n , n , n , n , y , n , y , n , n , y for i in range ( 0 , hou_d...
how to change string matrix to a integer matrix
Python
I am trying to predict the trend of an internet post.I have available the number of comments and votes the post has after 2 minutes of being posted ( can change , but it should be enough ) .Currently I use this formula : And then I find k experimentally . I get the post data , wait an hour , do And so on . This kind of...
predicted_votes = ( votes_per_minute + n_comments * 60 * h ) * k k = ( older_k + actual_votes/predicted_votes ) / 2 predicted_votes = ( ( votes_per_minute * x + n_comments * y ) * 60 * hour ) * k # Hour stands for 'how many hours to predict ' import numpy as np import matplotlib.pyplot as plt from scipy.optimize import...
Implementing a machine learning-like optimizer
Python
I have a series of functions that serve to classify data . Each function is passed the same input . The goal of this system is to be able to drop in new classification functions at will without having to adjust anything.To do this , I make use of a classes_in_module function lifted from here . Then , every classifier i...
class AbstractClassifier ( object ) : @ property def name ( self ) : return self.__class__.__name__class ClassifierA ( AbstractClassifier ) : def __init__ ( self , data ) : self.data = data def run ( self ) : return 1 result = [ ] for classifier in classifier_list : c = classifier ( data ) result.append ( c.run ( ) )
Fudging the line between classes and functions
Python
In R , ! is really an infix operator ` ! ` , so statements likeare totally valid . Is there a way to access the first order object underlying not in Python ? I have been googling with no success .
Map ( ` ! ` , c ( T , F , F ) )
What is python 's not ? A special function type ?
Python
Here is my sample data : Here is my desired output : I have created a new column called 'HP ' where I want to extract the horsepower figure from the original column ( 'Engine Information ' ) Here is the code I have tried to do this : The idea is I want to regex match the pattern : ' a sequence of numbers that come befo...
import pandas as pdimport re cars = pd.DataFrame ( { 'Engine Information ' : { 0 : 'Honda 2.4L 4 cylinder 190 hp 162 ft-lbs ' , 1 : 'Aston Martin 4.7L 8 cylinder 420 hp 346 ft-lbs ' , 2 : 'Dodge 5.7L 8 Cylinder 390hp 407 ft-lbs ' , 3 : 'MINI 1.6L 4 Cylinder 118 hp 114 ft-lbs ' , 4 : 'Ford 5.0L 8 Cylinder 360hp 380 ft-l...
Regular expression to find a sequence of numbers before multiple patterns , into a new column ( Python , Pandas )
Python
Suppose I have a timeseries of values called X.And I now want to know the first index after which the values of some other series Y will be reached by X . Or put differently , for each index i I want to know the first index j after which the line formed by X from j-1 to j intersects the value of Y at i.Below is an exam...
X | Y | Z2 | 3 | 22 | 3 | NaN4 | 4.5 | 35 | 5 | NaN4 | 5 | NaN3 | 2 | 61 | 2 | NaN
How do I find the index at which a given value will be reached/cross by another series ?
Python
I need to know if I can easily assign a variable within my script from a declaration in a text file . Basically , I want the user to be able to change the variable via the text file to match the numbers needed without having to fiddle with the source code.Text file input format : I simply want to load this into a list ...
faultInfo = [ [ [ `` L1603 '' ,1,5 ] , [ 271585,972739 ] , [ 272739,872739 , 272739,972739 , 271585,972739 , 271585,272389 , 270999,272389 ] ] , [ [ `` L1605 '' ,1,5 ] , [ 271897,872739 ] , [ 272739,872739 , 272739,972739 , 271891,872739 , 271891,272119 , 270963,272119 ] ] , [ [ `` L1607 '' ,1,4 ] , [ 271584,272738 ] ,...
Importing a 3-D list variable from a text file in Python
Python
Consider the following code : Is this a good idea , bad idea or should I just destroy myself ? If you 're wondering why I would want this , I got a function repeating itself every 4 seconds , using win32com.client.Dispatch ( ) it uses the windows COM to connect to an application . I think it 's unnecessary to recreate ...
def apples ( ) : print ( apples.applecount ) apples.applecount += 1apples.applecount = 0apples ( ) > > > 0apples ( ) > > > 1 # etc
Assigning a variable directly to a function in Python
Python
I have a pandas dataframe like this : I want to have only the top 3 characters in the dataframe and the remaining are combined as others so table become : How can I achieve this ? Thank you .
character count0 a 1041 b 302 c 2103 d 404 e 1895 f 206 g 10 character count0 c 2101 e 1892 a 1043 others 100
Combining rows to 'others ' in pandas
Python
I am trying to create a program that cycles through a string , This is what i have so far.This just gives me and so on till the last letter.This kind of does what i want but not fully.What i want this program to do is to print something like this.and so on ... .cycling thorugh the string , but i cant quite get it . Any...
def main ( ) : name = `` firstname lastname '' for i in name : print ( name ) name = name [ 1 : : ] main ( ) firstname lastnameirstname lastnamerstname lastnamestname lastnametname lastname firstname lastnameirstname lastname frstname lastname fistname lastname firtname lastname firsname lastname firstame lastname firs...
Python - Cycing through a string
Python
In strongly typed languages such as Java , there is no need to explicitly check the type of object returned since the code can not compile if the return types do not match method signature . Ex . You can not return a boolean when an integer is expected.In loosely typed languages such as Ruby , JavaScript , Python , etc...
module FirstModule TypeA = Struct.new ( : prop1 , : prop2 ) self.create_type_a TypeA.new ( 'prop1Val ' , 'prop2Val ' ) endend module TypeARepository def self.function_to_test FirstModule.create_type_a # This will return TypeA object endend RSpec.describe `` do describe `` do before do allow ( FirstModule ) .to receive ...
In unit testing loosely typed languages , should the return type of methods be checked ?
Python
I need to handle signals in my code and I am using global to share state between functions : Is there a way to avoid global variable in this case ? What is the best way to share state in this case ?
exit = Falsedef setup_handler ( ) : signal.signal ( signal.SIGTERM , handler ) def handler ( num , frame ) : global exit exit = Truedef my_main ( ) : global exit while not exit : do_something ( ) if __name__ == '__main__ ' : setup_handler ( ) my_main ( )
What is Pythonic way to share state inside one module ?
Python
Say I have the following dataframe df : And you want to check if , between columns A , B , and C , there is a common word , and create a column D with 1 if there is and 0 if there is n't any . For a word to be common , it 's enough for it to appear in just two of the three columns.The outcome should be : I am trying to...
A B C0 mom ; dad ; son ; sister ; son ; yes ; no ; maybe ; 1 dad ; daughter ; niece ; no ; snow ; 2 son ; dad ; cat ; son ; dad ; tree ; dad ; son ; 3 daughter ; mom ; niece ; referee ; 4 dad ; daughter ; cat ; dad ; A B C D0 mom ; dad ; son ; sister ; son ; yes ; no ; maybe ; 11 dad ; daughter ; niece ; no ; snow ; 02...
Python : determine if three text strings stored in a dataframe have any words in common
Python
I 'm trying to create a set of test cases for a project I 'm working on , and I 'd like to create all possible test cases and iterate through them ( quick program , should n't take long ) . The test cases should all be a list of length 1-4 and each item on the list should be an integer between 0-10 , inclusive . The fi...
[ 0 ] [ 0,0 ] [ 0,1 ] [ 0,2 ] [ 0,3 ] ... [ 0,10 ] [ 0,0,0 ] [ 0,0,1 ] [ 0,0,2 ] [ 0,0,3 ] ... [ 0,1,0 ] [ 0,1,1 ] [ 0,1,2 ] ... [ 0,10,10 ] ... [ 0,10,10,10 ] test_list = [ 0 ] for length in range ( 2 , 5 ) : while len ( test_list ) < length : test_list.append ( 0 ) for position in range ( 1 , length ) : for digit in ...
How to create list of all possible lists with n elements consisting of integers between 1 and 10 ?
Python
I have some acceleration data for which I am trying to count the length of sequences given a set of conditions . In this case I want to count the length of a sequence when the acceleration moves > 2.78 and then drops back below 0.An example would beThe return result here would be a count of 7 ( 2.88 , 2.86 , 2.53 , 1.9...
[ -1.1 , -1 , 0 , 1.2 , 1.8 , 2 , 2.88 , 2.86 , 2.53 , 1.98 , 1.21 , 0.89 , 0.11 , -0.21 ] def get_Accel_lengths ( array ) : s = `` .join ( [ ' 0 ' if i < 2.78 else ' 1 ' for i in resultsQ4 [ 'AccelInt ' ] ] ) parts = s.split ( ' 0 ' ) return [ len ( p ) for p in parts if len ( p ) > 0 ] Q4Accel = get_Accel_lengths ( r...
Length ( count ) of sequences with start and end condition Python
Python
If I have a this evaluates to True : but this evaluates to False : as doesWhy ? I found that getattr ( a , 'foo ' ) and a.foo both are represented by So no hint there ... .
class A : def foo ( self ) : pass getattr ( A , 'foo ' ) is A.foo a = A ( ) getattr ( a , 'foo ' ) is a.foo a.foo is a.foo < bound method A.foo of < __main__.A object at 0x7a2c4de10d50 > > )
Why does ` instance_of_object.foo is instance_of_object.foo ` evaluate False ?
Python
Suppose I have the following , which is the better , faster , more Pythonic methodand why ? or :
if x == 2 or x == 3 or x == 4 : do following ... if x in ( 2 , 3 , 4 ) : do following ...
Should I use 'in ' or 'or ' in an if statement in Python 3.x to check a variable against multiple values ?
Python
If I run the following code in a Python interpreter : Why is the result False ?
> > > object.__dict__ is object.__dict__False
Why is `` object.__dict__ is object.__dict__ '' False ?
Python
I 'm creating a script that 's actually an environment for other users to write code on . I 've declared several methods in a class and instantiate an object so users can use those methods as simple interpreter functions , like so : Since I do n't want the user to call the methods with fw.method1 ( arg ) , I setup alia...
from code import interactclass framework : def method1 ( self , arg1 ) : # code for method1 def method2 ( self , arg2 ) : # code for method2def main ( ) : fw = framework ( ) # Aliases method1 = fw.method1 method2 = fw.method2 interact ( local=locals ( ) )
How to alias all methods from an object ?
Python
I just encountered the following and am curious about Python 's behavior : In particular , why does ( 1 in range ( 2 ) ) == True evaluate True and l in range ( 2 ) == True evaluate to False ? It seems like there is some strange order of evaluation behavior in the latter , except that if you make the order explicitly wr...
> > > x = 1 > > > x in range ( 2 ) True > > > type ( x in range ( 2 ) ) < type 'bool ' > > > > x in range ( 2 ) == TrueFalse > > > x in range ( 2 ) == FalseFalse > > > ( x in range ( 2 ) ) == TrueTrue > > > x in ( range ( 2 ) == True ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > ...
Order of evaluation when testing equivalence of booleans
Python
The input is a sorted list of elements and an external item . For example : What is the fastest way of finding out which two elements in list_ item falls between ? In this case for example , the two numbers would be 3.5 and 5.8 . Any ideas ?
list_ = [ 0 , 3.5 , 5.8 , 6.2 , 88 ] item = 4.4
Fastest way to find which two elements of a list another item is closest to in python
Python
Given a string s representing characters typed into an editor , with `` - > '' representing a delete , return the current state of the editor.For every one `` - > '' it should delete one char . If there are two `` - > '' i.e `` - > - > '' it should delete 2 char post the symbol.Example 1ExplanationThe `` b '' got delet...
Inputs = `` a- > bcz '' Output '' acz '' Input s = `` - > x- > z '' Outputempty string def delete_forward ( text ) : '' '' '' return the current state of the editor after deletion of characters `` '' '' f = `` - > '' for i in text : if ( i==f ) : del ( text [ i+1 ] )
how to delete char after - > without using a regular expression
Python
This is from Leetcode 804 : Unique Morse Code Words . I am wondering why my code gives the right Morse code but it is sorted in alphabetic order which is not on purpose . Any contribution is appreciated.Input : code : output :
words = [ `` gin '' , `` zen '' , `` gig '' , `` msg '' ] class Solution : def uniqueMorseRepresentations ( self , words : List [ str ] ) - > int : morse = [ `` .- '' , '' - ... '' , '' -.-. '' , '' -.. '' , '' . '' , '' ..-. '' , '' -- . '' , '' ... . '' , '' .. '' , '' . -- - '' , '' -.- '' , '' .-.. '' , '' -- '' , ...
Why is string sorted in alphabetic order ?
Python
I have a sorted list of integers and I find want find to the number runs in this list . I have seen many examples when looking for numbers runs that increment by 1 , but I also want to look for number runs where the difference between numbers is customizable.For example , say I have the following list of numbers : Usin...
nums = [ 1 , 2 , 3 , 6 , 7 , 8 , 10 , 12 , 14 , 18 , 25 , 28 , 31 , 39 ] [ [ 1 , 2 , 3 ] , [ 6 , 7 , 8 ] , [ 10 ] , [ 12 ] , [ 14 ] , [ 18 ] , [ 25 ] , [ 28 ] , [ 31 ] , [ 39 ] ] [ [ 1 , 2 , 3 ] , [ 6 , 7 , 8 , 10 , 12 , 14 ] , [ 18 ] , [ 25 ] , [ 28 ] , [ 31 ] , [ 39 ] ] [ [ 1 , 2 , 3 , 6 , 7 , 8 , 10 , 12 , 14 ] , [ ...
Find number runs with customizable distance between numbers
Python
map and filter are often interchangeable with list comprehensions , but reduce is not so easily swapped out as map and filter ( and besides , in some cases I still prefer the functional syntax anyway ) . When you need to operate on the arguments themselves , though , I find myself going through syntactical gymnastics a...
[ afunc ( *i ) for i in aniter ] == map ( afunc , *zip ( *aniter ) ) [ afunc ( *i ) for i in aniter ] == map ( lambda i : apply ( afunc , i ) , aniter )
Can you apply an operation directly to arguments within map/reduce/filter ?
Python
Please help in troubleshooting python3 logging from multiple processes into same log file.i have dameon main script , which runs in back ground , and calls few other pythons scripts every 15seconds , and each python script is written with same TimedRotatingFileHandler attributes , and all logs are written into same log...
lib/├── __init__.py├── FIRST.py└── SECOND.py└── THIRD.pymain_daemon.py t1 = t2 = t3 = Thread ( ) my_thread = MYthreads ( t1 , t2 , t3 ) # # # # # # # # # # # # # # # # # Daemon Class # # # # # # # # # # # # # # # # # class Daemon ( Daemon ) : def run ( self ) : while True : my_thread.start_my_class ( ) time.sleep ( 15 ...
python3 : timedrotatingfilehandler log rotation issue with same log file with multiple scripts
Python
I have a matrix named xs : Now I want to replace the zeros by the nearest previous element in the same row ( Assuming that the first column must be nonzero. ) . The rough solution as following : Any help will be greatly appreciated .
array ( [ [ 1 , 1 , 1 , 1 , 1 , 0 , 1 , 0 , 0 , 2 , 1 ] , [ 2 , 1 , 0 , 0 , 0 , 1 , 2 , 1 , 1 , 2 , 2 ] ] ) In [ 55 ] : row , col = xs.shapeIn [ 56 ] : for r in xrange ( row ) : ... . : for c in xrange ( col ) : ... . : if xs [ r , c ] == 0 : ... . : xs [ r , c ] = xs [ r , c-1 ] ... . : In [ 57 ] : xsOut [ 57 ] : arra...
Is there some elegant way to manipulate my ndarray
Python
I have a below dataframe I would like to create a new column `` check '' that would be based on data in previous rows in dataframe : Find cell in action column = `` DONE '' Search for the first CREATED or UPDATED with the same id in previous rows , before DONE . In case its CREATED then put C in case UPDATED put U . Ou...
id action ================ 10 CREATED 10 111 10 222 10 333 10 DONE 10 222 10 UPDATED 777 CREATED 10 333 10 DONE id action check ================ 10 CREATED 10 111 10 222 10 333 10 DONE C 10 222 10 UPDATED 777 CREATED 10 333 10 DONE U
pandas dataframe column based on previous rows
Python
I want to fill a matrix from an array of indices : The result is : As desired.QuestionIs there a way to do this in pure python/numpy without looping ?
import numpy as npindx = [ [ 0,1,2 ] , [ 1,2,4 ] , [ 0,1,3 ] , [ 2,3,4 ] , [ 0,3,4 ] ] x = np.zeros ( ( 5,5 ) ) for i in range ( 5 ) : x [ i , indx [ i ] ] = 1. array ( [ [ 1. , 1. , 1. , 0. , 0 . ] , [ 0. , 1. , 1. , 0. , 1 . ] , [ 1. , 1. , 0. , 1. , 0 . ] , [ 0. , 0. , 1. , 1. , 1 . ] , [ 1. , 0. , 0. , 1. , 1 . ] ]...
Fill a matrix from a matrix of indices
Python
I have a dataset as follow : For each string I want to get the positions of first element and last element of each `` Uninterrupted S groups '' . For example , for first row I have 'DDDSSDSSDS ' ( as you see I have three groups of S ) and my favorite output for this `` S group '' s is something like [ ( 3,5 ) , ( 6,8 )...
data = { `` C1 '' : [ 'DDDSSDSSDS ' , 'SSDDDSSDDS ' , 'DDDDDDDDDD ' , 'SSSSSSSSSS ' , 'SSSSSSSDSS ' , 'DDDDDSDDDD ' , 'SDDDDDDDDD ' ] } dt = pd.DataFrame ( data ) print ( dt ) C1 C20 DDDSSDSSDS [ ( 3 , 5 ) , ( 6 , 8 ) , ( 9-10 ) ] 1 SSDDDSSDDS [ ( 0 , 2 ) , ( 5 , 7 ) , ( 9 , 10 ) ] 2 DDDDDDDDDD [ ] 3 SSSSSSSSSS [ ( 1 ,...
How to apply regex over all the rows of a dataset ?
Python
Assume yo = Yo ( ) is a big object with a method double , which returns its parameter multiplied by 2.If I pass yo.double to imap of multiprocessing , then it is incredibly slow , because every function call creates a copy of yo I think.Ie , this is very slow : Output : ... BUT , if I wrap yo.double with a function dou...
from tqdm import tqdmfrom multiprocessing import Poolimport numpy as npclass Yo : def __init__ ( self ) : self.a = np.random.random ( ( 10000000 , 10 ) ) def double ( self , x ) : return 2 * xyo = Yo ( ) with Pool ( 4 ) as p : for _ in tqdm ( p.imap ( yo.double , np.arange ( 1000 ) ) ) : pass 0it [ 00:00 , ? it/s ] 1it...
Passing a method of a big object to imap : 1000-fold speed-up by wrapping the method
Python
I am trying to understand a piece of Python code.First , I have the following file structure : The __init__.py in the folder folder1 has nothing.The __init__.py in the folder model has the following : With that said , I have some code in python that uses all the aboveNow , I am trying to understand the following codeMy...
folder1 -- model __init__.py file1.py file2.py __init__.py import osfiles = os.listdir ( os.path.split ( os.path.realpath ( __file__ ) ) [ 0 ] ) files.remove ( '__init__.py ' ) for file in files : if file.endswith ( '.py ' ) : exec ( 'from . { } import *'.format ( file [ : -3 ] ) ) from folder1 import model as mymodel ...
Trying to understand __init__.py combined with getattr
Python
I am subclassing a type defined in a C module to alias some attributes and methods so that my script works in different contexts . How is it that to get this to work , I have to tweak the dictionary of my class manually ? If I do n't add a reference to DistanceTo in the dictionnary , I get Point3d has no attribute name...
class Point3d ( App.Base.Vector ) : def __new__ ( cls , x , y , z ) : obj = super ( Point3d , cls ) .__new__ ( cls ) obj.x , obj.y , obj.z = x , y , z obj.__dict__.update ( { ' X ' : property ( lambda self : self.x ) , ' Y ' : property ( lambda self : self.y ) , ' Z ' : property ( lambda self : self.z ) , 'DistanceTo '...
Method ignored when subclassing a type defined in a C module
Python
After having tried many things , I thought it would be good to ask on SO . My problem is fairly simple : how can I solve the following equation using Sympy ? EquationI want to solve this for lambda_0 and q is an array of size J containing elments between 0 and 1 that sum op to 1 ( discrete probability distribution ) . ...
from sympy.solvers import solvefrom sympy import symbols , summationp = [ 0.2 , 0.3 , 0.3 , 0.1 , 0.1 ] l = symbols ( ' l ' ) j = symbols ( ' j ' ) eq= summation ( j*q [ j ] / ( l-j ) , ( j , 0 , 4 ) ) s= solve ( eq , l )
Solve equation with sum and index using Sympy
Python
I have a list : I want to swap 12 and 89 such that the list should lookWhen I do it this wayNothing is changedBut when I do it this wayIt works perfectSo why it is n't working the first way ? PS-The whole reason I want to do the first way is because I want to find the max element in a list and then swap it with the fir...
lis = [ 12,45,15,67,89 ] lis = [ 89,45,15,67,12 ] lis [ 0 ] , lis [ lis.index ( 89 ) ] = lis [ lis.index ( 89 ) ] , lis [ 0 ] lis = [ 12,45,15,67,89 ] lis5 [ 0 ] , lis5 [ 4 ] = lis5 [ 4 ] , lis5 [ 0 ] lis = [ 89,45,15,67,12 ] max1 = max ( lis ) lis [ 0 ] , lis [ lis.index ( max1 ) ] = lis [ lis.index ( max1 ) ] , lis [...
Swaping two elements in a list shows unexpected behaviour
Python
I have a node system where every node only stores its inputs and outputs , but not its index . Here is a simplified example : Now I want to order that nodes , so that all inputs are already processed when processing that node . For this simple example , a possible order would be [ Node1 , Node2 , Node3 , Node4 ] . My f...
class Node1 : requiredInputs = [ ] class Node2 : requiredInputs = [ `` Node1 '' ] class Node3 : requiredInputs = [ `` Node2 '' ] class Node4 : requiredInputs = [ `` Node3 '' , `` Node2 '' ]
Sort nodes based on inputs / outputs
Python
im new to python and trying to one hot encode . My code is below : I am trying to one hot encode the service subcodes ( ssc ) associated to each ID . where lets say id 1895650 has two ssc 's 2,4 then the encoding should be 0101 . But as you see in my code the output shows as 0101000 for some reason . I do not need the ...
import pandas as pdfrom operator import adddf = pd.DataFrame ( [ [ 1895650,2 , float ( `` nan '' ) , `` 2018-07-27 '' ] , [ 1895650,4 , float ( `` nan '' ) , `` 2018-08-13 '' ] , [ 1896355,2 , float ( `` nan '' ) , `` 2018-08-10 '' ] , [ 1897675,9,12.0 , '' 2018-08-13 '' ] , [ 1897843,2 , float ( `` nan '' ) , '' 2018-...
Strange Hot encoding issue with function in Python
Python
I have two pieces of code that seem to do the same thing but one is almost a thousand times faster than the other one.This is the first piece : In ts I have values like : In contrast , this part of the code : Creates ts populated with the values like : I can not figure out what the essential difference is between the f...
t1 = time.time ( ) df [ new_col ] = np.where ( df [ col ] < j , val_1 , val_2 ) t2 = time.time ( ) ts.append ( t2 - t1 ) 0.0007321834564208984 , 0.0002918243408203125 , 0.0002799034118652344 t1 = time.time ( ) df [ 'new_col ' ] = np.where ( ( df [ col ] > = i1 ) & ( df [ col ] < i2 ) , val , df.new_col ) t2 = time.time...
Why is changing values in a column of a pandas data frame fast in one case and slow in another one ?
Python
From the code here : https : //www.learnsteps.com/increasing-performance-python-code/which produces this output : Can someone provide a better explanation than 'function lookups are costly ' as to why creating a function prototype close to the use of the function is somehow faster ? ( This does n't work for most functi...
import datetime alist = [ str ( x ) for x in range ( 100000000 ) ] print ( `` \nStandard loop . '' ) a = datetime.datetime.now ( ) result = [ ] for item in alist : result.append ( len ( item ) ) b = datetime.datetime.now ( ) print ( ( b-a ) .total_seconds ( ) ) print ( `` \nStandard loop with function name in local nam...
Python : Why does copying the function name to a local namespace result in a faster access
Python
Still new to python and coding , only about 6 weeks into this adventure . I started a finance project to try and figure out what % of the portfolio should be in cash , and how much should be invested based on the current market performance . No idea if this research will have any relevance but it has been helpful getti...
if ( current_market_status == 0 ) : # all time high record current_cash_required_equity = 0.3 elif ( current_market_status < -0.05 ) : # less than 5 % current_cash_required_equity = 0.25 elif ( current_market_status < -0.10 ) : # less than 10 % current_cash_required_equity = 0.20 elif ( current_market_status < -0.15 ) ...
Looking for some guidance on combinatorics in python
Python
Given the DataFrame generated by : df : I need to , for each id , remove rows which are more than 24hours ( 1 day ) from the latest time_entered , for that id . My current solution : which gives the correct , expected , output : However , my real data is tens of millions of rows , and hundreds of thousands of unique id...
import numpy as npimport pandas as pdfrom datetime import timedeltanp.random.seed ( 0 ) rng = pd.date_range ( '2015-02-24 ' , periods=14 , freq='9H ' ) ids = [ 1 ] *5 + [ 2 ] *2 + [ 3 ] *7df = pd.DataFrame ( { 'id ' : ids , 'time_entered ' : rng , 'val ' : np.random.randn ( len ( rng ) ) } ) id time_entered val0 1 2015...
Efficient way of filtering by datetime in groupby
Python
I have the following trees ( tree_1 , tree_2 , tree_3 ) stored in a dictionary ( dict_1 , dict_2 , dict_3 ) . How can I recursively traverse all the paths of the tree , collecting all the nodes from the root to the last node of each branch ? In other words , I would like to generate a list of all the possible sequences...
[ [ `` FunctionDef '' , `` try '' , `` ExceptHandler '' , `` Expr '' , `` Call '' , `` Attribute '' , '' Load '' ] , [ `` FunctionDef '' , `` try '' , `` ExceptHandler '' , `` Expr '' , `` Call '' , `` Attribute '' , '' save_dictionary '' ] , [ `` FunctionDef '' , `` try '' , `` ExceptHandler '' , `` Expr '' , `` Call ...
Problems while traversing and extracting the nodes of a tree ?
Python
I have a dataframe belowand it is like this : There are some consecutive duplicated values ( ignore the Date value ) within each 'ID ' ( Name ) , e.g . line 1 and 2 for James , the From_num are both 420 , same as line 9 and 10 , I wish to drop the 2nd duplicated row and keep the first . I wrote loop conditions , but it...
df = pd.DataFrame ( { 'ID ' : [ 'James ' , 'James ' , 'James ' , 'James ' , 'Max ' , 'Max ' , 'Max ' , 'Max ' , 'Max ' , 'Park ' , 'Park ' , 'Park ' , 'Park ' , 'Tom ' , 'Tom ' , 'Tom ' , 'Tom ' ] , 'From_num ' : [ 578 , 420 , 420 , 'Started ' , 298 , 78 , 36 , 298 , 'Started ' , 28 , 28 , 311 , 'Started ' , 60 , 520 ,...
Pandas drop consecutive duplicate rows only , ignoring specific columns
Python
I 'm new to python , and I have a simple question.say I make a subclass of str to change everything into 'test ' : all I want is 'test ' , but where does python store the original value '12345 ' ? I can not find it anywhere.after checking this , I actually find it in getnewargsthen I change this to : why is 12345 still...
class Mystr ( str ) : def __str__ ( self ) : return 'test ' def __repr__ ( self ) : return 'test ' > > > mystr = Mystr ( 12345 ) > > > print ( mystr ) test > > > > > > print ( mystr + 'test ' ) 12345test > > > dir ( mystr ) [ '__add__ ' , '__class__ ' , '__contains__ ' , '__delattr__ ' , '__dict__ ' , '__dir__ ' , '__d...
where does python store origin value for str
Python
I have a list of variables , and a function object and I would like to assign the correct number of variable depending on the function.so if f = sum2 , I would like it to call first 2 elements of varList , and if f = sum3 , to call it with 3 elements of the function .
def sum2 ( x , y ) : return x + ydef sum3 ( x , y , z ) : return x + y + zvarList = [ 1,2,3 ]
python - enter the correct number of variables based on function handle
Python
Here is MRE : What I am trying to do is loop through each dictionary and append each value to a column in a dataframe.right now I am doingoutputting : Yes this is what I want however I have over 1M dictionaries in a list . Is it most efficient way ? EDIT : pd.DataFrame ( data ) .rename ( columns= { ' 1 ' : 'col1 ' } ) ...
data = [ { ' 1':20 } , { ' 1':10 } , { ' 1':40 } , { ' 1':14 } , { ' 1':33 } ] import pandas as pdlst = [ ] for item in data : lst.append ( item [ ' 1 ' ] ) df = pd.DataFrame ( { `` col1 '' : lst } ) col10 201 102 403 144 33 data = [ { ' 1 ' : { 'value':20 } } , { ' 1 ' : { 'value':10 } } , { ' 1 ' : { 'value':40 } } ,...
Efficient way of looping through list of dictionaries and appending items into column in dataframe