lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I have this while loop , and I was wondering if their is a more pythonic way to write it : s is a numpy vector . Thanks ! | k = 1while np.sum ( s [ 0 : k ] ) / s_sum < retained_variance : k += 1 | Is there are more pythonic way to write a while loop that only updates a variable ? |
Python | In a slightly contrived experiment I wanted to compare some of Python 's built-in functions to those of numpy . When I started timing these though , I found something bizarre.When I wrote the following : I would get two different results in almost random alternation in a very statistically significant way.This alternat... | import timeittimeit.timeit ( 'import math ; math.e**2 ' , number=1000000 ) [ timeit.timeit ( 'import math ; math.e**2 ' , number=1000000 ) for i in xrange ( 100 ) ] test = ( timeit.timeit ( 'import math ; math.e**2 ' , number=1000000 ) for i in xrange ( 100 ) ) [ item for item in test ] timeit.timeit ( 'math.e**2 ' , '... | Two very different but very consistent results from Python timeit |
Python | I 've encountered some ( mysterious ? ) performance issue on NumPy matrix-vector multiplication.I wrote the following snippet to test the speed of matrix-vector multiplication : In some machines , the result is normal : In some machines , the multiplication slowed down at size 96 : Some even slowed down by a factor of ... | import timeitfor i in range ( 90 , 101 ) : tm = timeit.repeat ( 'np.matmul ( a , b ) ' , number = 10000 , setup = 'import numpy as np ; a , b = np.random.rand ( { 0 } , { 0 } ) , np.random.rand ( { 0 } ) '.format ( i ) ) print ( i , sum ( tm ) / 5 ) 90 0.0893646227999852291 0.0887211905997901492 0.0908306845996776293 0... | Performance drop in NumPy matrix-vector multiplication |
Python | I am trying to remove words that have length below 2 and any word that is numbers . For exampleOutput desired isI tried \w { 2 , } this removes all the word whose length is below 2 . When I added \D+ this removes all numbers when I did n't want to get rid of 2 from test2 . | s = `` This is a test 1212 test2 '' `` This is test test2 '' | How can I remove numbers , and words with length below 2 , from a sentence ? |
Python | As an example , I have the following dataframe : My goal is to add one column 'Counter ' that basically shows a balance of the number of A 's and B 's . So , every time an A appears , the counter column increases one value . Every time B appears , the counter column decreases one value . If two A 's appear at the same ... | Date Balance2013-04-01 03:50:00 A2013-04-01 04:00:00 A2013-04-01 04:15:00 B2013-04-01 04:15:00 B2013-04-01 04:25:00 A2013-04-01 04:25:00 A2013-04-01 04:35:00 B2013-04-01 04:40:00 B2013-04-02 04:55:00 B2013-04-02 04:56:00 A2013-04-02 04:57:00 A2013-04-03 10:30:00 A2013-04-03 16:35:00 A2013-04-03 20:40:00 A Date Balance ... | Python - Counter in 2 million row table |
Python | I have two lists and I need to do a combination of strings from these lists , I have tried but I think it 's not very efficient for larger lists.My Output is : Is there any more pythonic way to achieve it ? | data = [ 'keywords ' , 'testcases ' ] data_combination = [ 'data ' , 'index ' ] final_list = [ ] for val in data : for comb in range ( len ( data_combination ) ) : if comb == 1 : final_list.append ( [ val ] + data_combination ) else : final_list.append ( [ val , data_combination [ comb ] ] ) [ [ 'keywords ' , 'data ' ]... | Combination of lists from two lists of strings |
Python | I have a dataframe and a dictionary : And I would like to clean the VALUE column according to the accepted ranges in the dictionary.I have tried : using map ( ) but I ca n't seem to find a way to use it by VARIABLE groups . apply ( ) would work , I think , however , apply ( ) works really slow with my dataframe ( > 10M... | df = VARIABLE VALUEA 3A 4A 60A 5B 1B 2B 3B 100C 0C 1 # inclusiveaccepted_ranges= { A : [ 3,5 ] , B : [ 1,3 ] } df = VARIABLE VALUEA 3A 4A NaNA 5B 1B 2B 3B NaNC 0C 1 | Filter numeric column by dictionary of value ranges |
Python | I have Query which shows different results when i use and or & I always have been using : But in this particular case when i use & it always outputs a single row . ( I also checked print q.query ( ) , query comes out to be fine ) However , when i use and instead of & . Query gives correct output what actually is happen... | criteria1 = Q ( id__gte=802 , id__lte=1000 ) criteria2 = Q ( country_id__contains='UK ' ) q = Mymodel.objects.filter ( criteria1 & criteria2 ) q = Mymodel.objects.filter ( criteria1 and criteria2 ) | Difference between using 'and ' and using ' & ' in Django ORM |
Python | I have a data set as following : My goal is this : I want to combine same apps for each user based on same time or if it is in 5 minute interval and saving only earliest time stamp . Expected output : Mike had run chrome.exe 3 times but the interval was < = 5 so we want to count it as once . While John ran chrome.exe 2... | Name | Time | App -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -Mike 2019-05-10 21:10 chrome.exeMike 2019-05-10 21:10 chrome.exeMike 2019-05-10 21:12 chrome.exeJohn 2019-05-10 18:09 chrome.exeJohn 2019-05-10 18:25 chrome.exe Name | Time | App -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -Mike 2019-05-10 21:10 chr... | How to remove same values based on time using interval ? |
Python | I want to parse logic strings and get all the combinations of elements that are in an `` and '' logic . For instance , for the string ' ( A and ( B or C ) ) ' I should get [ [ A , B ] , [ A , C ] ] and for the string ' ( A and B and ( C or D and F ) or F and G ) ' I should get [ [ A , B , C ] , [ A , B , D , F ] , [ F ... | import pyparsing as ppcomplex_expr = pp.Forward ( ) vars = pp.Word ( pp.alphas , pp.alphanums + `` _ '' ) | pp.Regex ( r '' [ +- ] ? \d+ ( : ? \.\d* ) ? ( : ? [ eE ] [ +- ] ? \d+ ) ? `` ) .setName ( 'proteins ' ) clause = pp.Group ( vars ^ ( pp.Suppress ( `` ( `` ) + complex_expr + pp.Suppress ( `` ) '' ) ) ) expr = pp... | get elements in `` AND '' in logic string with Python |
Python | I 'd like to get idea why should I use kwargs or args over passing in a simple dict ( or tuple in case of args ) ? I wrote a very simple code snippet to check what exactly happens and I ca n't find any pros to use kwargs over a dict . If anyone could tell me why should I use those I 'd be happy.Now as I can see it just... | def test_normal ( input : dict ) : for element in input.items ( ) : print ( 'Type : { } , raw : { } '.format ( type ( input ) , input ) ) print ( 'key : { } , value : { } '.format ( element [ 0 ] , element [ 1 ] ) ) def test_kwargs ( **kwargs ) : for element in kwargs.items ( ) : print ( 'Type : { } , raw : { } '.forma... | What is the benefit of using kwargs ( or args ) over a simple dict ? |
Python | Can this Python code be improved ? | def build_list ( types ) : for x in types : for a in [ 'short ' , 'long ' , 'average ' ] : for b in [ 'square ' , 'sloped ' , 'average ' ] : for c in [ 'small ' , 'large ' , 'average ' ] : for d in [ 'thin ' , 'thick ' , 'average ' ] : for e in [ 'high ' , 'low ' , 'average ' ] : for f in [ True , False ] : for g in [ ... | Can this Python script be improved ? |
Python | How 'pythonic-ly ' , do I turn this : Into : | [ [ x1 , y1 ] , [ x2 , y2 ] ] [ ( x1 , x2 ) , ( y1 , y2 ) ] | List of lists in to list of tuples , reordered |
Python | I am trying to find out if I can execute certain buildsteps on another machine than the build client in the same build . For instance , one path of the build process includes that the final zip should just be packaged if 2 other machines did run successfully a unit test . Can someone point me to a link or explain how t... | ( client3 ) ↗ unittest ↘ ( client2 ) ↗ other tests ↘ ( client1 ) → git sync → compile → sign executables → zip → publish | Executing buildsteps in buildbot on other clients |
Python | It seems that my program is trying to learn until a certain point , and then it 's satisfied and stops improving and changing at all . With my testing it usually goes to a value of -5 at most , and then it remains there no matter how long I keep it running . The result set does not change either.Just to keep track of i... | import osimport neatdef main ( genomes , config ) : networks = [ ] ge = [ ] choices = [ ] for _ , genome in genomes : network = neat.nn.FeedForwardNetwork.create ( genome , config ) networks.append ( network ) genome.fitness = 0 ge.append ( genome ) choices.append ( [ ] ) for x in range ( 25 ) : for i , genome in enume... | Python NEAT not learning further after a certain point |
Python | I have a text file with the format ( date , time , resistance ) : I need to extract the value of resistance ( third column ) from every 6 seconds after the first data entry . To start I wanted to import the text file using : However before I 've hardly begun my program , I get the error : ValueError : invalid literal f... | 12/11/2013 13:20:38 28.321930E+3 ... ... ... date , time , resistance = loadtxt ( 'Thermometers.txt ' , unpack=True , usecols= [ 0,1,2 ] ) | Select entry from array given another value |
Python | Let 's suppose I have a bit of Python code : This script prints `` Daughter '' . Is there anyway to ensure that all of the __init__ methods of the bases classes are called ? One method I came up with to do this was : This script prints `` Daughter '' , `` Mother '' , `` Father '' . Is there a nice way to do this using ... | class Mother : def __init__ ( self ) : print ( `` Mother '' ) class Father : def __init__ ( self ) : print ( `` Father '' ) class Daughter ( Mother , Father ) : def __init__ ( self ) : print ( `` Daughter '' ) super ( ) .__init__ ( ) d = Daughter ( ) class Daughter ( Mother , Father ) : def __init__ ( self ) : print ( ... | Is there a way to use super ( ) to call the __init__ method of each base class in Python ? |
Python | I 'm trying to implement this curve as part of the leveling system of a small game I 'm currently working on . The equation is as followsWhich in python can be defined asRunning this function in the Python console returns the values expected . I ported it over to Java , where it takes the form of : However , mysterious... | f ( x ) = -e^- ( ( -log ( 7 ) /100 ) * ( 100-x ) ) +7 f=lambda x : -e**- ( ( -log ( 7 ) /100.0 ) * ( 100-x ) ) +7 public static double f ( float x ) { return ( Math.pow ( -Math.E , - ( ( -Math.log ( 7 ) /100 ) * ( 100-x ) ) ) +7 ) ; } | The equation -e**- ( ( -log ( 7 ) /100.0 ) * ( 100-x ) ) +7 returns NaN |
Python | I got a syntax error in 'Position : 5 ' . I ca n't find the source of the error as not knowing where 'the Position 5 ' indicates . How can I recognize the problematic line in the original code by reading the error code ? And , what does the v3 mean ? Error code | Exception : @ error : Model Expression *** Error in syntax of function string : Invalid element : < boundmethodgkvariable .dtof1 > Position : 5 v3- ( < boundmethodgkvariable.dtof1 > ) ? import numpy as npfrom gekko import GEKKOm = GEKKO ( ) nt = 101m.time = np.linspace ( 0,1 , nt ) # Variablesx1 = m.Var ( value=1 ) x2 ... | How to read the gekko error code ( e.g . Position : 5 , v3 etc ) |
Python | I 'm taking my first computing science course , and we just learned about class implementation and inheritance . In particular , we just covered method overriding and how classes we define inherit from the object superclass by default . As one of my examples trying out this particular case of inheritance , I used the f... | class A : def __init__ ( self , i ) : self.i = i def __str__ ( self ) : return `` A '' # Commenting out these two lines to not override __eq__ ( ) , just use the # default from our superclass , object # def __eq__ ( self , other ) : # return self.i == other.ix = A ( 2 ) y = A ( 2 ) > > > print ( x == y ) False > > > pr... | Python : case where x==y and x.__eq__y ( ) return different things . Why ? |
Python | I have been reading python documentation , could someone help me with interpreting this ? I initially thought it meant that try statements had to have either formats try And finally ortry , except , else AND finally.But after reading the documentation , it mentioned that else is optional and so is finally . So , I was ... | try_stmt : := try1_stmt | try2_stmttry1_stmt : := `` try '' `` : '' suite ( `` except '' [ expression [ ( `` as '' | `` , '' ) identifier ] ] `` : '' suite ) + [ `` else '' `` : '' suite ] [ `` finally '' `` : '' suite ] try2_stmt : := `` try '' `` : '' suite `` finally '' `` : '' suite | Try statement syntax |
Python | Repeated slicing works on tuples and lists just fine : But with strings : The weird thing here is , when I try repeated slicing over string name variable , there is nothing at name [ 0 ] [ 0 ] or name [ 0 ] [ -1 ] , so why does it show `` u '' ? And if something is at name [ 0 ] [ 0 ] then why not on other indexes ? | > > > tuple = ( `` nav '' , `` yad '' ) > > > tuple [ 0 ] 'nav ' > > > tuple [ 0 ] [ 0 ] ' n ' > > > name= '' university '' > > > name [ 0 ] ' u ' > > > name [ 0 ] [ 0 ] ' u ' > > > name [ 0 ] [ -1 ] ' u ' > > > name [ 0 ] [ 1 ] Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > IndexEr... | Slicing a string repeatedly |
Python | I need to convert hundreds of html sentences generated by an outside source to readable text , and I have a question about conversion of abbr tag . Below is an example : This code returns `` WHO is a specialized agency of the UN. '' . However , what I want is `` WHO ( World Health Organization ) is a specialized agency... | from bs4 import BeautifulSouptext = `` < abbr title=\ '' World Health Organization\ '' style=\ '' color : blue\ '' > WHO < /abbr > is a specialized agency of the < abbr title=\ '' United Nations\ '' style=\ '' color : # CCCC00\ '' > UN < /abbr > . `` print ( BeautifulSoup ( text ) .get_text ( ) ) | How to convert html ` abbr ` tag text to a text in parentheses in Python ? |
Python | When I write What is happening ? why does n't it do this for any fl ? How do I avoid this ? It looks \xef\xac\x82 is not , in fact , fl . Is there any way to 'translate ' this character into fl ( as the author intended it ) , without just excluding it via something like | > > > st = `` Piperazine ( perphenazine , fluphenazine ) '' > > > st'Piperazine ( perphenazine , \xef\xac\x82uphenazine ) ' unicode ( st , errors='ignore ' ) .encode ( 'ascii ' ) | fluphenazine read as \xef\xac\x82uphenazine |
Python | I am trying to randomly assign values from one column in one dataframe , to another dataframe within 12 different categories ( by agerange and gender ) . For example I have two dataframes ; lets call one d1 and the other d2 I want to group both dataframes by agerange and gender i.e 0-1,2,3,4,5,6 & 1-1,2,3,4,5,6 then ra... | d1 : index agerange gender income 0 2 1 56700 1 2 0 25600 2 4 0 3000 3 4 0 106000 4 3 0 200 5 3 0 43000 6 4 0 10000000d2 : index agerange gender 0 3 0 1 2 0 2 4 0 3 4 0 d1 : index agerange gender income 0 2 1 56700 1 2 0 25600 2 4 0 3000 3 4 0 106000 4 3 0 200 5 3 0 43000 6 4 0 10000000d2 : index agerange gender income... | How to assign values randomly between dataframes |
Python | This is a bit of a follow-up to this question.Why is locality determined at compile time and not at execution time ? Is it purely for performance ? Are there languages that look up their variables at execution time ? I.e . every time a variable is accessed , this variable is first searched in the local scope and then t... | def f ( ) : print ( ' f ' ) def g ( ) : f ( ) f = 42g ( ) | Why is locality determined at compile time ? |
Python | I have got a list of 2d coordinates with this structure : Where coo [ 0 ] is the first coordinate stored in a tuple.I would like to choose two different random coordinates . I can of course use this method : But because I have to repeat this operation 1'000'000 times I was wondering if there is a faster method to do th... | coo = [ ( 0 , 0 ) , ( 0 , 1 ) , ( 0 , 2 ) , ( 1 , 0 ) , ( 1 , 1 ) , ( 1 , 2 ) , ( 2 , 0 ) ] import numpy as nprndcoo1 = coo [ np.random.randint ( 0 , len ( coo ) ) ] rndcoo2 = coo [ np.random.randint ( 0 , len ( coo ) ) ] if rndcoo1 ! = rndcoo2 : # do something | Which is the more efficient way to choose a random pair of objects from a list of lists or tuples ? |
Python | How can I find the length of the longest connected interval chain ? Example : Here the longest chain would be : As you can see , the end of the current interval should be the start of the next interval.I would like to find the length of the longest chain in the sense : length= ( 12- ( -4 ) ) =16I think this involves re... | [ -4,1 ] [ 1,5 ] [ 2,10 ] [ 3,5 ] [ 1,3 ] [ 3,8 ] [ 8,12 ] [ 5,11 ] [ -4,1 ] [ 1,3 ] [ 3,8 ] [ 8,12 ] | Python : How to find longest continuous interval with connected interval start and end |
Python | In resume , I have two keys in the same dictionary where each one has their corresponding lists.I try to compare both list to check common and differential elements . It means that the output I will count how many elements are identical or present in only one key 's list.from the beginning I am inserting the elements u... | def shared ( list ) : dict_shared = { } for i in list : infile = open ( i , ' r ' ) if i not in dict_shared : dict_shared [ i ] = [ ] for line in infile : dict_shared [ spacer ] .append ( record.id ) return dict_shared dict = { a : [ 1,2,3,4,5 ] , b : [ 2,3,4,6 ] } a : [ 1,5 ] b : [ 6 ] a-b : [ 2,3,4 ] | Compare lists in the same dictionary of lists |
Python | I have a list of strings like such , Given a keyword list like [ 'for ' , 'or ' , 'and ' ] I want to be able to parse the list into another list where if the keyword list occurs in the string , split that string into multiple parts.For example , the above set would be split into Currently I 've split each inner string ... | [ 'happy_feet ' , 'happy_hats_for_cats ' , 'sad_fox_or_mad_banana ' , 'sad_pandas_and_happy_cats_for_people ' ] [ 'happy_feet ' , 'happy_hats ' , 'cats ' , 'sad_fox ' , 'mad_banana ' , 'sad_pandas ' , 'happy_cats ' , 'people ' ] | Splitting a string based on a certain set of words |
Python | I am creating a simple pyramid-based CMS that uses traversal . There is a class called Collection , that has some subclasses like NewsCollection , GalleriesCollection etc.I need two kinds of views to display these collections . The frontent , html view and the backend , json view ( the admin panel uses dgrid to display... | @ view_config ( context=Collection , xhr=True , renderer='json ' , accept='application/json ' ) | Can a view configured for superclass be used if a view for a class was configured in Pyramid ? |
Python | I 'm trying to create a list that pulls ten random real numbers between 30 and 35 and prints them out on a list . When I run the below code I get the following error : TypeError : 'float ' object is not iterable.Here 's the code : I feel like I 'm missing something obvious.When I run the code withoutI get the results I... | lis = list ( range ( 10 ) ) random.seed ( 70 ) for i in range ( 0 , len ( lis ) ) : randreal = ( random.random ( ) *5 + 30 ) lis = list ( randreal ) print ( lis ) lis=list ( randreal ) print ( lis ) | Turning a random.random ( ) result into a list - Python |
Python | I have some points in the interval [ 0,20 ] I have a window of size window_size=3 that I can move inside the above interval . Therefore the beginning of the window - let 's call start is constrained to [ 0,17 ] .Let 's say we have some points below : If we wanted a minimum of min_points=4 points the solution of the sta... | points = [ 1.4,1.8 , 11.3,11.8,12.3,13.2 , 18.2,18.3,18.4,18.5 ] suitable_starts = [ [ 10.2,11.3 ] , [ 15.5,17.0 ] ] get_start_windows ( interval = [ 0,20 ] , window_size = 3.0 , points = [ 1.4,1.8,11.3,11.8,12.3,13.2,18.2,18.3,18.4,18.5 ] , min_points = 4 return suitable_starts # suitable_starts = [ [ 10.2,11.3 ] , [ ... | Numpy finding interval which has a least k points |
Python | EDIT : Problem solved ! Thank you to user limbo for your input . It was not the solution , but led me down right path : my LEFT JOIN was showing all null posts ! I have also included the if-defined check , as a good back-up check . Goal : On a message post dashboard , only show delete-post button if the logged-in user ... | { % for message in messages : % } //'mu_id ' is messages.user_id as defined in server.py //'user [ 0 ] [ 'id ' ] is logged-in user id //using 'session [ 'id ' ] instead produces same ( unwanted ) results { % if message [ 'mu_id ' ] == user [ 0 ] [ 'id ' ] : % } // show delete button ( this part worked , do n't worry ) ... | Python - Show delete button only if user owns post |
Python | I know how to remove the first occurrence of a letter using splicing , but I 'm trying to achieve this without using any of the string functions like splicing , .find ( ) , .count ( ) , etc . I ca n't seem to figure out how you complete it without splicing . Here 's what I currently have with splicing that works correc... | s1 = `` s2 = len ( remWord ) for i in range ( s2 ) : if ( remWord [ i ] == remLetter ) : s1 = remWord [ 0 : i ] + remWord [ i + 1 : s2 ] return s1 | How to remove first occurrence of a letter ? |
Python | I 'm currently writing a small script using pygame , but I do n't believe this question to be related strictly to pygame.I have a class that holds a dictionary of function parameters contained in tuples : In the same class , I have a function that issues a call to another function using these parameters : It works , bu... | self.stim = { 1 : ( firstParam , secondparam , thirdparam ) , 2 : ( firstParam2 , secondparam2 , thirdparam2 ) , 3 : ( firstParam3 , secondParam3 , thirdParam3 ) } def action ( self , stimType ) : pygame.draw.rect ( self.stim [ stimType ] [ 0 ] , self.stim [ stimType ] [ 1 ] , self.stim [ stimType ] [ 2 ] ) | Is there a more pythonic way of storing parameters so they can be used in a function call ? |
Python | Why is it that when the code is run through python the graph seems to break down at 10^-1 on the y-axis ? ( Code below ) What it should look like : What it actually looks like : I am currently running python 2.7 on Xubuntu 14.04 , and this error happens on many histograms . For some reason when opened and run through P... | from pylab import *bins = [ +0.000e+00 , +1.000e+00 , +2.000e+00 , +3.000e+00 , +4.000e+00 , +5.000e+00 ] wght = [ [ +3.000e-02 , +7.0e-02 , +3.0e-01 , +5.0e-01 , +8.0e-01 ] ] hist ( [ bins [ : -1 ] for i in range ( len ( wght ) ) ] , bins=bins , weights=wght , histtype= '' stepfilled '' , log=True ) ylim ( bottom=0.01... | matplotlib stepfilled histogram breaks at the value 10^-1 on xubuntu |
Python | Given an index array I , how to I set the values of a data array D whose indices do n't exist in I ? Example : How to I get A from I and D ? Edit : I 'm looking for how to do this in one shot for cases where I and d are big . | I = array ( [ [ 1,1 ] , [ 2,2 ] , [ 3,3 ] ] ) D = array ( [ [ 1 , 2 , 3 , 4 , 5 , 6 ] , [ 7 , 8 , 9 , 1 , 2 , 3 ] , [ 4 , 5 , 6 , 7 , 8 , 9 ] , [ 1 , 2 , 3 , 4 , 5 , 6 ] , [ 7 , 8 , 9 , 1 , 2 , 3 ] ] ) A = array ( [ [ 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 8 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 6 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 4 , 0 ... | How do I do this array indexing in numpy |
Python | The following python code calculates the number of iterations to do stuff based on some variables . The variables will all be of the same type , that is only ints or floats or whatever . My concern is whether it will work correctly if the values are floats . I know enough to always consider the pitfalls of relying on e... | # a - b - c is always a multiple of d. i = ( a - b - c ) / d while i : # do stuff i -= 1 | Floating point arithmetics : Possible unsafe reliance on specific comparison ? |
Python | I have a sequence of generators : ( gen_0 , gen_1 , ... gen_n ) These generators will create their values lazily but are finite and will have potentially different lengths.I need to be able to construct another generator that yields the first element of each generator in order , followed by the second and so forth , sk... | ( ( 1 , 4 , 7 , 10 , 13 , 16 ) , ( 2 , 5 , 8 , 11 , 14 ) , ( 3 , 6 , 9 , 12 , 15 , 17 , 18 ) ) [ i for t in zip ( *a ) for i in t ] | Traversing a sequence of generators |
Python | I have to find all strings which are made of only letters ' a ' and ' b ' and every instance of ' a ' is immediately followed by ' b ' and immediately preceded by ' b'.For example : Then my regex should return : ( In string 'ab ' - ' a ' is not preceded by ' b ' . Similarly for 'aba ' and 'xyz ' is not made of only ' a... | mystring = 'bab babab babbab ab baba aba xyz ' [ 'bab ' 'babab ' 'babbab ' ] re.findall ( r ' ( ( ? < =b ) a ( ? =b ) ) ' , mystring ) [ ' a ' , ' a ' , ' a ' , ' a ' ] | How to capture the entire string while using 'lookaround ' with chars in regex ? |
Python | Say I have two lists ( always the same length ) : I have the following rules for intersections and unions I need to apply when comparing these lists element-wise : Thus , the desired output is : While this works , I need to do this with several hundred very large lists ( each , with thousands of elements ) , so I am lo... | l0 = [ 0 , 4 , 4 , 4 , 0 , 0 , 0 , 8 , 8 , 0 ] l1 = [ 0 , 1 , 1 , 1 , 0 , 0 , 0 , 8 , 8 , 8 ] # union and intersectuni = [ 0 ] *len ( l0 ) intersec = [ 0 ] *len ( l0 ) for i in range ( len ( l0 ) ) : if l0 [ i ] == l1 [ i ] : uni [ i ] = l0 [ i ] intersec [ i ] = l0 [ i ] else : intersec [ i ] = 0 if l0 [ i ] == 0 : un... | How to vectorize this operation |
Python | I tried solving this problem for 2 days already , read like 50 questions in StackOverflow and a lot of documentation about Python . I do n't know what else to try.My CodeBasically what it should do is : When I press Shift+A mute everyone in every voice channel.When I press Shitf+B unmute everyone in every voice channel... | import discordimport refrom datetime import datetimeimport mysql.connectorfrom discord.ext import commands , tasksfrom discord.utils import getimport atexitfrom pynput import keyboardimport asynciofrom asgiref.sync import async_to_sync , sync_to_async # The currently active modifierscurrent = set ( ) # The key combinat... | Need to await a function inside a sync function |
Python | I am using the below code to display x and y values on plotly dash . But then i want to be be able to add a another text field below the `` value '' textfield.The text field would be called `` Category '' so that if the y value displayed is:5k then category = not pricey or if value is 20k then category = average price ... | import jsonfrom textwrap import dedent as dimport pandas as pdimport plotly.graph_objects as goimport numpy as npimport dashimport dash_core_components as dccimport dash_html_components as htmlimport plotly.express as pxfrom dash.dependencies import Input , Outputfrom jupyter_dash import JupyterDash # app infoapp = Jup... | Plotly : How to edit text output based on value retrieved by hovering ? |
Python | From this link i learnt that The current implementation keeps an array of integer objects for all integers between -5 and 256 , when you create an int in that range you actually just get back a reference to the existing objectBut when I tried to give some example for my session and i found out that it behaves different... | Python 2.7.2 ( default , Oct 11 2012 , 20:14:37 ) [ GCC 4.2.1 Compatible Apple Clang 4.0 ( tags/Apple/clang-418.0.60 ) ] on darwinType `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > a , b = 300,300 > > > a is bTrue > > > c = 300 > > > d = 300 > > > c is dFalse > > > | How the tuple unpacking differ from normal assignment ? |
Python | I want to remove the django.contrib.comments app from a project I 'm working on . I tried : on the shell but got : Error : App with label django.contrib.comments could not be found . Are you sure your INSTALLED_APPS setting is correct ? I have double checked my INSTALLED_APPS setting and indeed django.contrib.comments ... | $ python manage.py sqlclear django.contrib.comments | Completely removing a django app that has dot notation |
Python | I have this dataframe : df : Where I 'm looking for this output : I have seen similar questions for categorical types columns , but not for indexes and I 'm looking for a way to avoid using the method reset_index ( ) as actually I 'm using four indexes and not just two as in the minimal example . Any suggestions ? | df = pd.DataFrame ( { 'NUMBER_1 ' : { ( '2019-07 ' , ' A ' ) : 4 , ( '2019-07 ' , 'D ' ) : 2 , ( '2019-08 ' , ' A ' ) : 32 , ( '2019-08 ' , ' B ' ) : 14 , ( '2019-09 ' , ' A ' ) : 32 , ( '2019-09 ' , ' B ' ) : 53 , ( '2019-09 ' , ' C ' ) : 54 , ( '2019-09 ' , 'D ' ) : 24 } , 'NUMBER_2 ' : { ( '2019-07 ' , ' A ' ) : 75 ... | Reindex MultiIndex with unique values in level |
Python | I have the command heroku run -a $ { { secrets.HEROKU_APP_NAME } } python manage.py migrate set to run after pushing master to Heroku . It runs without errors ( below is it 's the output ) : But the migrations do n't actually run . What could be the problem ? | Running python manage.py migrate on *** ... ? Running python manage.py migrate on *** ... done | Django migrations not working from GitHub Actions |
Python | Given an arbitrary picklable Python data structure data , isequivalent to i.e . can I assume this equivalence when writing code ? Could you describe how you reached to this conclusion ? The use-case is to separate serialization from writing , since I may want to write pickle to a non-disk location . | with open ( ' a ' , 'bw ' ) as f : f.write ( pickle.dumps ( data ) ) with open ( ' a ' , 'bw ' ) as f : pickle.dump ( data , f ) | Is ` pickle.dump ( d , f ) ` equivalent to ` f.write ( pickle.dumps ( d ) ) ` ? |
Python | The variable a can take any number of values . The value of a is the amount of extra pre-defined conditions to have for the while loop.This can be done with multiple elif statements but is there a cleaner way of doing this ? | if a == 0 : while condition_1 : ... elif a == 1 : while condition_1 or condition_2 : ... elif a == 2 : while condition_1 or condition_2 or condition_3 : ... | Have extra while loop conditions ... based on a condition ? |
Python | My function foo accepts an argument things which is turned into a list internally.The list constructor accepts any iterable.However , annotating things with typing.Iterable does not give the user a clue that the iterable must be finite , not something like itertools.count ( ) .What 's the correct type hint to use in th... | def foo ( things ) : things = list ( things ) # more code | Type Hint for finite iterable |
Python | While installing Python 3.4.4 into Linux server by running ./configure script and getting the following error : I am trying to search but not getting that much information , could experts provide here their views , will be grateful to you . | checking for ensurepip ... upgradeconfigure : creating ./config.statusconfig.status : error : can not find input file : ` Makefile.pre.in ' | Getting an error while installing Python 3.4.4 in Linux |
Python | I have a list which can contain both Nones and datetime objects . I need to split this in sublists of consecutive datetime objects and need to record the index of the first datetime object of this sublist in the original list.E.g. , I need to be able to turn into : I have tried two approaches . One using find : and one... | original = [ None , datetime ( 2013 , 6 , 4 ) , datetime ( 2014 , 5 , 12 ) , None , None , datetime ( 2012 , 5 , 18 ) , None ] ( 1 , [ datetime.datetime ( 2013 , 6 , 4 , 0 , 0 ) , datetime.datetime ( 2014 , 5 , 12 , 0 , 0 ) ] ) ( 5 , [ datetime.datetime ( 2012 , 5 , 18 , 0 , 0 ) ] ) binary = `` .join ( ' 1 ' if d else ... | Split list on None and record index |
Python | I 've noticed funny results with complex infinities.This is nan related . But the end result is bizarre.Is it a numpy bug ? Anything I should do differently ? | In [ 1 ] : import numpy as npIn [ 2 ] : np.isinf ( 1j * np.inf ) Out [ 2 ] : TrueIn [ 3 ] : np.isinf ( 1 * 1j * np.inf ) Out [ 3 ] : TrueIn [ 4 ] : np.isinf ( 1j * np.inf * 1 ) Out [ 4 ] : False | Why do NumPy operations with complex infinities lead to funny results ? |
Python | for example my xml file contains : and I want to retrieve an object from the xmlfor example returned object structure be like this | < layout name= '' layout1 '' > < grid > < row > < cell colSpan= '' 1 '' name= '' cell1 '' / > < /row > < row > < cell name= '' cell2 '' flow= '' horizontal '' / > < /row > < /grid > < /layout > class layout ( object ) : def __init__ ( self ) : self.grid=Noneclass grid ( object ) : def __init__ ( self ) : self.rows= [ ]... | Is there any way or any framework in python to create an object model from a xml ? |
Python | This could be a very silly question but I tried to google keywords like less and greater signs in data type of numpy and found no reference.In the doc of numpy , outputsBut on my PC , the output isWhat do < and > in the dtype mean and why there is the difference ? | x = np.array ( [ ( 1.0 , 2 ) , ( 3.0 , 4 ) ] , dtype= [ ( ' x ' , float ) , ( ' y ' , int ) ] ) array ( [ ( 1.0 , 2 ) , ( 3.0 , 4 ) ] , dtype= [ ( ' x ' , ' < f8 ' ) , ( ' y ' , ' < i4 ' ) ] ) array ( [ ( 1.0 , 2 ) , ( 3.0 , 4 ) ] , dtype= [ ( ' x ' , ' > f8 ' ) , ( ' y ' , ' > i4 ' ) ] ) | | , > and < in numpy datatype |
Python | I 've recently stumbled upon coding task , and I 've struggled to get it right . It goes like this : Given a non-empty string s and a list word_list containing a list of non-empty words , determine if s can be segmented into a space-separated sequence of one or more dictionary words . You may assume the word_list does ... | s = 'whataniceday'word_list = [ ' a ' , 'what ' , 'an ' , 'nice ' , 'day ' ] s = `` whataniceday '' word_list = [ `` h '' , `` a '' , `` what '' , `` an '' , `` nice '' , `` day '' ] def can_be_segmented ( s , word_list ) : tested_str = s buildup_str = `` for letter in tested_str : buildup_str += letter if buildup_str ... | Check if string can be splitted into sentence using words in provided list |
Python | In a jupyter notebook I have a bash jupyter cell as follows : I would like to access $ MYVAR in a different python cell . For exampleI would expect the cell to print `` something '' , but I get a NameError message . Example image : | % % bashexport MYVAR= '' something '' print ( MYVAR ) | access variable declared in a % % bash cell from another jupyter cell |
Python | I wrote two functions to check if a number ( Integer ) is a Palindrome or not.The first function reverses the number without affecting the datatype whereasthe second function converts the numbers into string , reverses the string , then converts it back into an Integer to compare the given number.Approach # 1Approach #... | def is_palindrome ( n ) : `` '' '' This function checks if a number is a Palindrome or not. `` '' '' result = 0 temp = n while temp > 0 : result *= 10 result += temp % 10 temp //= 10 return result == n def is_palindrome_str ( n ) : `` '' '' This function checks if a number is a Palindrome or not. `` '' '' return int ( ... | Optimized way for checking if the given number is a Palindrome |
Python | What is Python doing in its godforsaken hidden logics that makes that first statement False , while the rest are True ? | > > > 3 > 2 == True False # say what ? > > > ( 3 > 2 ) == True True > > > 3 > ( 2 == True ) True > > > 3 > 1 == True True > > > 3 > False True | Can someone explain to me what python is doing here ? |
Python | Supposing that I am applying a gaussian process regression to my data . Before fitting the model , I will perform some sort of feature engineering . After the model is fit , my goal is to now apply a minimization , which I intend to constrain for some values , over the curve in order to find the optimal X . However , h... | # X ( theta , alpha1 , alpha2 ) array ( [ [ 9.07660169 , 0.61485493 , 1.70396493 ] , [ 9.51498486 , -5.49212002 , -0.68659511 ] , [ 10.45737558 , -2.2739529 , -2.03918961 ] , [ 10.46857663 , -0.4587848 , 0.54434441 ] , [ 9.10133699 , 8.38066374 , 0.66538822 ] , [ 9.17279647 , 0.36327109 , -0.30558115 ] , [ 10.36532505 ... | How to perform a constrained optimization over a scaled regression model ? |
Python | Python amateur here . I have a text file that lists information on thousands of lines and I 'm trying to select a line and the following 2-3 lines based on whether they match a pattern . I 've filtered the file down from the original to just contain the parts of the file of interest to me so my current file looks like ... | trig1.RESP : stim4 : silence.wav trig1.RESP : trig6.RESP : 1 trig1.RESP : trig1.RESP : trig5.RESP : 1stim5 : silence.wavtrig1.RESP : trig6.RESP : 1stim3 : silence.wavtrig1.RESP : stim5 : silence.wavtrig1.RESP : trig6.RESP : 1 parsed_output = open ( `` name-of-file-to-be-written '' , `` w '' ) filtered_input = open ( ``... | Issue with selecting multiple lines of a txt document and write to new text doc in python |
Python | While trying to figure out if a function is called with the @ decorator syntax , we realized that inspect has a different behaviour when looking at a decorated class that inherits from a superclass.The following behaviour was found with CPython 3.6.2 under Windows 10.It was also reproduced in CPython 3.7.0 under Linux ... | import inspectdef decorate ( f ) : lines = inspect.stack ( ) [ 1 ] .code_context print ( f.__name__ , lines ) return f @ decorateclass Foo : pass @ decorateclass Bar ( dict ) : pass Foo [ ' @ decorate\n ' ] Bar [ 'class Bar ( dict ) : \n ' ] | Why does inspect return different line for class inheriting from superclass ? |
Python | I 'm trying to create a list of available ports in Python . I am following this tutorial , but instead of printing the open ports , I 'm adding them to a list.Initially , I had something like the following : This clearly works fine , but it is well known that comprehensions are faster than loops , so I now have : I ass... | available_ports = [ ] try : for port in range ( 1,8081 ) : sock = socket.socket ( socket.AF_INET , socket.SOCK_STREAM ) result = sock.connect_ex ( ( remoteServerIP , port ) ) if result == 0 : available_ports.append ( port ) sock.close ( ) # ... try : available_ports = [ port for port in range ( 1 , 8081 ) if not socket... | Why are sockets closed in list comprehension but not in for loop ? |
Python | I am rearranging some Ordered Dictionary based on the key from a list . Such in : Now I have a list of the group 's order.and get the result with the items in the dictionary grouped together , as such : I found some excellent related question How to reorder OD based on list and Re-ordering OrderedDict and I am going wi... | old_OD = OrderedDict ( [ ( 'cat_1',1 ) , ( 'dog_1',2 ) , ( 'cat_2',3 ) , ( 'fish_1',4 ) , ( 'dog_2',5 ) ] ) order = [ 'dog ' , 'cat ' , 'fish ' ] new_OD = OrderedDict ( [ ( 'dog_1',2 ) , ( 'dog_2',5 ) , ( 'cat_1',1 ) , ( 'cat_2',3 ) , ( 'fish_1',4 ) ] ) new_od = OrderedDict ( [ ( k , None ) for k in order if k in old_o... | How to rearrange an Ordered Dictionary with a based on part of the key from a list |
Python | The Problem : I 've implemented Knuth 's DLX `` dancing links '' algorithm for Pentominoes in two completely different ways and am still getting incorrect solutions . The trivial Wikipedia example works OK ( https : //en.wikipedia.org/wiki/Knuth % 27s_Algorithm_X # Example ) , but more complex examples fail.Debugging t... | l_0,0_rr10|100111100001000000l_0,1_rr10|100011110000100000l_1,1_rr10|100000000111100001l_0,0_rr01|100111101000000000l_0,1_rr01|100011110100000000l_1,0_rr01|100000001111010000l_0,0_rr30|100100001111000000l_1,0_rr30|100000001000011110l_1,1_rr30|100000000100001111l_0,1_rr01|100000010111100000l_1,0_rr01|100000000001011110l... | Debug Exact Cover Pentominoes , Wikipedia example incomplete ? OR ... I 'm misunderstanding something ( includes code ) |
Python | Suppose I have a dataframe df as : -I want to remove all the rows from the dataframe where address is subset of another address and company is same . Eg , I want these two rows out of above 5 rows . | index company url address 0 A . www.abc.contact.com 16D Bayberry Rd , New Bedford , MA , 02740 , USA 1 A . www.abc.contact.com . MA , USA 2 A . www.abc.about.com . USA 3 B . www.pqr.com . New Bedford , MA , USA 4 B. www.pqr.com/about . MA , USA index company url address 0 A . www.abc.contact.com 16D Bayberry Rd , New B... | How to remove rows based on a column value where some row 's column value are subset of another ? |
Python | So I 'm getting some interesting behaviour from some filters stacked within a for loop.I 'll start with a demonstration : Here we get the expected output . We have a range within a filter within a filter , and the filter conditions are stacking as we want them to . Now here comes my problem.I have written a function fo... | > > > x = range ( 100 ) > > > x = filter ( lambda n : n % 2 == 0 , x ) > > > x = filter ( lambda n : n % 3 == 0 , x ) > > > list ( x ) [ 0 , 6 , 12 , 18 , 24 , 30 , 36 , 42 , 48 , 54 , 60 , 66 , 72 , 78 , 84 , 90 , 96 ] def relative_primes ( num ) : `` 'Returns a list of relative primes , relative to the given number .... | Odd behavior of stacked filter ( ) calls |
Python | I have found 2 ways of counting the lines of a file as they can be seen below . ( note : I need to read the file as a whole and not line-by-line ) Trying to get a feel of which approach is better in terms of efficiency and/or good-coding-style . ( as seen here ) ( as seen here ) And in the same topic , regarding the co... | names = { } for each_file in glob.glob ( '*.cpp ' ) : with open ( each_file ) as f : names [ each_file ] = sum ( 1 for line in f if line.strip ( ) ) data = open ( 'test.cpp ' , ' r ' ) .read ( ) print ( len ( data.splitlines ( ) ) , len ( data.split ( ) ) , len ( data ) ) | Preffered way of counting lines , characters and words from a file as a whole in Python |
Python | Anyone can explain me why thisreturns thisinstead of What to do to return only the version number without `` Python `` ? | python -V | awk ' { print $ 2 } ' Python 2.7.5 2.7.5 | how to retun only python version |
Python | I am using Python , Pandas for data analysis . I have sparsely distributed data in different columns like followingI want to combine this sparsely distributed data in different columns to tightly packed column like following.What I have tried is doing following , but not able to do it properlyBut I think there must be ... | | id | col1a | col1b | col2a | col2b | col3a | col3b || -- -- | -- -- -- -| -- -- -- -| -- -- -- -| -- -- -- -| -- -- -- -| -- -- -- -|| 1 | 11 | 12 | NaN | NaN | NaN | NaN || 2 | NaN | NaN | 21 | 86 | NaN | NaN || 3 | 22 | 87 | NaN | NaN | NaN | NaN || 4 | NaN | NaN | NaN | NaN | 545 | 32 | | id | group | cola | colb ... | Pandas combining sparse columns in dataframe |
Python | ProblemI want to identify when I 've encountered a true value and maintain that value for the rest of the array ... for a particular bin . From a Numpy perspective it would be like a combination of numpy.logical_or.accumulate and numpy.logical_or.at.ExampleConsider the truth values in a , the bins in b and the expected... | a = np.array ( [ 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 ] ) .astype ( bool ) b = np.array ( [ 0 , 0 , 0 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 2 , 3 , 3 , 0 , 1 , 2 , 3 ] ) # zeros ↕ ↕ ↕ ↕ ↕ ↕ ↕ # ones ↕ ↕ ↕ ↕ ↕ # twos ↕ ↕ # threes ↕ ↕ ↕c = np.array ( [ 0 , 0 , 0 , 0 , 1 , 1 , 1 , 0 , 1 , 1 , 0 , 0 , ... | cumulative logical or within bins |
Python | I have survey data which annoying has returned multiple choice questions in the following way . It 's in an excel sheet There is about 60 columns with responses from single to multiple that are split by / . This is what I have so far , is there any way to do this quicker without having to do this for each individual co... | data = { 'q1 ' : [ 'one ' , 'two ' , 'three ' ] , 'q2 ' : [ 'one/two/three ' , ' a/b/c ' , 'd/e/f ' ] , 'q3 ' : [ ' a/b/c ' , 'd/e/f ' , ' g/h/i ' ] } df = pd.DataFrame ( data ) df [ [ 'q2a ' , 'q2b ' , 'q2c ' ] ] = df [ 'q2 ' ] .str.split ( '/ ' , expand = True , n=0 ) df [ [ 'q3a ' , 'q3b ' , 'q3c ' ] ] = df [ 'q2 ' ... | split multiple columns in pandas dataframe by delimiter |
Python | I 've been stuck on a line of my code for a while , and I 'm at a loss as to why it returns as it does.This returnsWhereas my goal is a return ofMy previous solution was to loop through the list with an increasing value for the index , and to individually check each entry in word against the guess , and to replace the ... | guess = ' a'word = [ ' a ' , ' b ' , ' c ' ] board = [ ' _ ' , ' _ ' , ' _ ' ] board = list ( map ( lambda x : guess if word [ board.index ( x ) ] == guess else x , board ) ) print ( board ) [ ' a ' , ' a ' , ' a ' ] [ ' a ' , ' _ ' , ' _ ' ] | replacing list items that fit condition in lambda |
Python | Suppose I have a certain list x with numbers , and another list y with other numbers . Elements of y should be elements of x , but due to noise in measurements , they are kind of different . I want to find , for each value of y , the value of x that is the nearest to it.I can do this with some loops and check , for eac... | x_in = [ 1.1 , 2.2 , 3 , 4 , 6.2 ] y_in = [ 0.9 , 2 , 1.9 , 6 , 5 , 6 , 6.2 , 0.5 , 0 , 3.1 ] desired_output = [ 1.1 , 2.2 , 2.2 , 6.2 , 4 , 6.2 , 6.2 , 1.1 , 1.1 , 3 ] y_out = [ ] for y in y_in : aux = [ abs ( l - y ) for l in x_in ] mn , idx = min ( ( aux [ i ] , i ) for i in range ( len ( aux ) ) ) y_out.append ( x_... | Round each number of list to most near number in another list |
Python | I 'm trying to get input from a user using the Walrus operator : = , but if the user will only type in the Enter key as input , than the python script will terminate . How can I catch this error and make sure that the user has n't only pressed the Enter key ? There is this answer but it does not work using the walrus o... | while True : answer = input ( `` Please enter something : `` ) if answer == `` '' : print ( `` Invalid ! Enter key was pressed . '' ) continue else : print ( `` Enter was n't pressed ! '' ) # do something while answer : = input ( `` Please enter something : `` ) : # if user pressed only ` Enter ` script will terminate ... | How to check if the Enter key was pressed while using the Walrus operator in Python ? |
Python | The code has been taken from Learning Python 4th Edition by Mark LutzAlso , when I run this code , it does n't print the sum of 1,2,3 either , but in the book , it 's shown that it does ! I am left scratching my head at this entire code . I have no idea what is going on in here . | class tracer : def __init__ ( self , func ) : self.calls = 0 self.func = func def __call__ ( self , *args ) : self.calls += 1 print ( 'call % s to % s ' % ( self.calls , self.func.__name__ ) ) self.func ( *args ) @ tracerdef spam ( a , b , c ) : print ( a + b + c ) spam ( 1 , 2 , 3 ) | May someone explain this decorator code to me ? |
Python | I 'm Trying to optimize my code , and I got into a problem I do n't quite understand . On every page of my web app , there will be a list of notifications much like Facebook 's new ticker . So , on every request , I run this code in the beggining : Then , where I find a good spot , I call the middle function which is :... | notification_query = db.Query ( Ticker , keys_only=True ) \ .filter ( 'friends = ' , self.current_user.key ( ) .name ( ) ) self._notifications_future = notification_query.run ( ) notification_keys = [ future.parent ( ) for future in self._notifications_future ] self._notifications = db.get_async ( notification_keys ) c... | Why is my RPC total going up ? |
Python | As far as I understand Python destructors should be called when the reference count of an object reaches 0 . But this assumption seems not to be correct . Look at the following code : OutputsBut A has a reference to B , so I would expect the following output : What am I not getting ? | class A : def __init__ ( self , b ) : self.__b = b print ( `` Construct A '' ) def __del__ ( self ) : # It seems that the destructor of B is called here . print ( `` Delete A '' ) # But it should be called here class B : def __init__ ( self ) : print ( `` Construct B '' ) def __del__ ( self ) : print ( `` Delete B '' )... | Python destructor called in the `` wrong '' order based on reference count |
Python | I want to merge consecutive NaN values into slices . Is there a simple way of doing this with numpy or pandas ? Expected result : A numpy array with two dimensions would be OK as well , rather than a list of tuplesUpdate 2019/05/31 : I have just realised that if I just use a dictionary instead of a Pandas Series the al... | l = [ ( 996 , np.nan ) , ( 997 , np.nan ) , ( 998 , np.nan ) , ( 999 , -47.3 ) , ( 1000 , -72.5 ) , ( 1100 , -97.7 ) , ( 1200 , np.nan ) , ( 1201 , np.nan ) , ( 1205 , -97.8 ) , ( 1300 , np.nan ) , ( 1302 , np.nan ) , ( 1305 , -97.9 ) , ( 1400 , np.nan ) , ( 1405 , -97.10 ) , ( 1408 , np.nan ) ] l = pd.Series ( dict ( ... | How to group consecutive NaN values from a Pandas Series in a set of slices ? |
Python | Suppose I have N generators gen_1 , ... , gen_N where each on them will yield the same number of values . I would like a generator gen such that it runs gen_1 , ... , gen_N in N parallel processes and yields ( next ( gen_1 ) , next ( gen_2 ) , ... next ( gen_N ) ) That is I would like to have : in such a way that each ... | def gen ( ) : yield ( next ( gen_1 ) , next ( gen_2 ) , ... next ( gen_N ) ) A = range ( 4 ) def gen ( a ) : B = [ ' a ' , ' b ' , ' c ' ] for b in B : yield b + str ( a ) def target ( g ) : return next ( g ) processes = [ Process ( target=target , args= ( gen ( a ) , ) ) for a in A ] for p in processes : p.start ( ) f... | Given N generators , is it possible to create a generator that runs them in parallel processes and yields the zip of those generators ? |
Python | Coming from the beautiful world of c , I am trying understand this behavior : would not even finish after 20 minutes , and I know that the list sizes is not that big , less than 205k in length . However this executed instantly : So what happened ? My guess : python could not understand that min ( sizes ) will be always... | In [ 1 ] : dataset = sqlContext.read.parquet ( 'indir ' ) In [ 2 ] : sizes = dataset.mapPartitions ( lambda x : [ len ( list ( x ) ) ] ) .collect ( ) In [ 3 ] : for item in sizes : ... : if ( item == min ( sizes ) ) : ... : count = count + 1 ... : In [ 8 ] : min_item = min ( sizes ) In [ 9 ] : for item in sizes : if ( ... | Is python smart enough to replace function calls with constant result ? |
Python | I want to find the mode of the task column in this dataframe : If there are multiple modes , I want to display all of them.Can someone please help me get this output : This is my first question here . Any help or hint is greatly appreciated . Thank you . | + -- -- -+ -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -+| id | task |+ -- -- -+ -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -+| 101 | [ person1 , person1 , person3 ] || 102 | [ person1 , person2 , person3 ] || 103 | null || 104 | [ person1 , person2 ] || 105 | [ person1 , person1 , pers... | How to find multi mode of an array column in Pyspark |
Python | I am currently doing manual python code refactoring.In order to be sure that I break nothing in the original code by forgetting to correct the instructions I enclose within functions , I want to be sure that the function can have no access to the global variables when I am testing them . What would be the right way to ... | def big_function ( args ) : def one_small_transformation ( args ) : # No one else needs to see this transformation outside the function1 def second_small_transformation ( args ) : ... # Block of instructions chaining small transformations # Other big functions and code making them work together | Is there a way to forbid a python function to use any variable except local ones ? |
Python | I find myself writing assertions like these : I was wondering if there 's a way to write a function that would accept a valid Python expression and an exception class as an input , evaluate the expression , and if it finds it to be false , print out the representation of each of the lowest-level terms in the expression... | if f ( x , y ) ! = z : print ( repr ( x ) ) print ( repr ( y ) ) print ( repr ( z ) ) raise MyException ( 'Expected : f ( x , y ) == z ' ) # validate is the mystery functionvalidate ( ' f ( x , y ) == z ' , MyException ) | python : automatically printing representation of each component in an expression |
Python | We have a python application that loads a config.yml with aumbry . For production purpose we need to encrypt this configuration with fernet , which aumbry can load seamlessly.We want to be able to load both unencrypted and encrypted in a transparent way , for example load unencrypted if found , and if not ( production ... | import cryptography.Fernet as fnfrom os.path import split , splitextdef _encrypt_file ( path , key ) : with open ( path , 'rb ' ) as infile : file_data = infile.read ( ) nc_data= fn ( key ) .encrypt ( file_data ) infile.close ( ) base_path , filename = split ( path ) name , _ = splitext ( filename ) nc_name = `` { } . ... | Support both encrypted and non encrypted configuration with aumbry |
Python | I recently discovered that the following returns True : I 'm aware of the python comparison chaining such as a < b < c , but I ca n't see anything in the docs about this being legal.Is this an accidental feature in the implementation of CPython , or is this behaviour specified ? | ' a ' in 'ab ' in 'abc ' | Where in the python docs does it allow the ` in ` operator to be chained ? |
Python | Original DataSetGiven a dataframe , I would like a flexible , efficient way to reset specific values based on certain conditions in two columns . Conditions : in Column B : for any row with value ' x ' , in Column C : set the value of these row-elements to the value of the next row.Desired OutcomeI learned I can accomp... | In [ 2 ] : import pandas as pd ... : ... : # Original DataSet ... : d = { ' A ' : [ 1,1,1,1,2,2,2,2,3 ] , ... : ' B ' : [ ' a ' , ' a ' , ' a ' , ' x ' , ' b ' , ' b ' , ' b ' , ' x ' , ' c ' ] , ... : ' C ' : [ 11,22,33,44,55,66,77,88,99 ] , } ... : ... : df = pd.DataFrame ( d ) ... : dfOut [ 2 ] : A B C0 1 a 111 1 a ... | Can I set dataframe values without using iterrows ( ) ? |
Python | I 'm looking for the fastest way to do the following : We have a pd.DataFrame : That looks like : What I want to know is which one of the High1 , High2 , High3 float values is the first that is larger or equal to the High value . If there is none , it should be np.nanAnd the same for the Low1 , Low2 , Low3 value , but ... | df = pd.DataFrame ( { 'High ' : [ 1.3,1.2,1.1 ] , 'Low ' : [ 1.3,1.2,1.1 ] , 'High1 ' : [ 1.1 , 1.1 , 1.1 ] , 'High2 ' : [ 1.2 , 1.2 , 1.2 ] , 'High3 ' : [ 1.3 , 1.3 , 1.3 ] , 'Low1 ' : [ 1.3 , 1.3 , 1.3 ] , 'Low2 ' : [ 1.2 , 1.2 , 1.2 ] , 'Low3 ' : [ 1.1 , 1.1 , 1.1 ] } ) In [ 4 ] : dfOut [ 4 ] : High High1 High2 High... | Fastest way to find which of two lists of columns of each row is true in a pandas dataframe |
Python | I have a program that takes 2 numbers and subtracts them and also tells us if the individual places i.e . ones , tens and hundreds are smaller than the number they are being subtracted from and if they need to borrow.And this is my output : Here is my question:1 ) I want to map the results to a list of dictionary for e... | a=2345b=1266o= [ int ( d ) for d in str ( a ) ] a= [ int ( d ) for d in str ( a ) ] b= [ int ( d ) for d in str ( b ) ] x=len ( a ) y=len ( b ) i=1state= [ ] c= [ ] for n in range ( x ) : if a [ x-i ] < b [ y-i ] : a [ x-i ] +=10 a [ x-i-1 ] -=1 state.append ( True ) else : state.append ( False ) i+=1i=1 for m in range... | How to convert several lists to a list of dicts in python ? |
Python | I have a list of tuples like : and I need to convert it to : Is that possible in Python ? Thanks ! | [ ( 1 , ' a ' , 22 ) , ( 2 , ' b ' , 56 ) , ( 1 , ' b ' , 34 ) , ( 2 , ' c ' , 78 ) , ( 3 , 'd ' , 47 ) ] { 1 : { ' a ' : 22 , ' b ' : 34 } , 2 : { ' b ' : 56 , ' c ' : 78 } , 3 : { 'd ' : 47 } } | How to convert a list of tuples to a dictionary of dictionaries in Python ? |
Python | I have started learning pandas and got stumbled at the below problem : Following is a table which has data like : Book : UCODE : The requirement is to use the if..else logic to pull the data from the above mentioned tables.Req . : Excepted O/P : Any help/tutorial where I can get some insight to achieve the expected out... | B_IDX B_NAME B_AUTHOR B_PRICE B_UTYPE B_ID1 ABC aaa 12.21 SCI 1822 BCD bbb 98 ECN 9203 CDE ccc 22.34 SCI 2284 DEF ddd 44.11 LIT 7615 EFG eee 0.99 MAT 102426 FGH fff 4.99 MAT 77721 U_ID U_CD182 9982825950 9992822228 9999983776 9912876332 9003931 if B_UTYPE == 'SCI ' : pull the record from 'UCODE'elif B_UTYPE == 'MAT ' :... | How to use if-else in pandas dataframes |
Python | I just want to know which way is more preferable in python.Imagine two functions:1 function:2 function : As you can see the only difference is else statement . So the question is will it affect performance somehow . Or are there any reasons to include else in this type of functions ? | def foo ( key ) : if bar.has_key ( key ) : return bar.get ( key ) # do something with bar # this will be executed if bar_key ( key ) is False ... return something def foo ( key ) : if bar.has_key ( key ) : return bar.get ( key ) else : # do something with bar # this will be executed if bar_key ( key ) is False ... retu... | Which of these two functions more `` pythonic '' ? |
Python | I found several questions on this topic but none that addressed the problem I am seeing . I apologize in advance I 'm new to python . What I am trying to do is count the number of files in every directory beneath somedir/ so I would get something like : I thought the easiest way to prove I could do this would be : But ... | dir-a : 13dir-b : 6dir-c : 21 from os import listdirfrom os.path import isfile , isdirdef walk ( p ) : for file in listdir ( p ) : if isfile ( file ) : print ( `` File : `` + file ) elif isdir ( file ) : print ( `` Dir : `` + file ) walk ( file ) else : print ( `` Unknown : `` + file ) path = raw_input ( 'Enter path to... | printing number of files per directory python |
Python | I have a raw text file containing only the following line , and no newline : The characters are escaped as shown above , meaning that the \u05E9 is really a backslash , followed by 5 alphanumeric characters ( and not an Unicode character ) . I am trying to decode the file using the following code : Using print is not p... | Q853 \u0410\u043D\u0434\u0440\u0435\u0439 \u0410\u0440\u0441\u0435\u043D\u044C\u0435\u0432\u0438\u0447 \u0422\u0430\u0440\u043A\u043E\u0432\u0441\u043A\u0438\u0439 import codecswith codecs.open ( `` wikidata-terms20.nt '' , ' r ' , encoding='unicode_escape ' ) as input : with open ( `` wikidata-terms3.nt '' , `` w '' )... | Unicode-escaped file processing error |
Python | I have seen people using [ : ] to make a swallow copy of a list , like : I understand that . However , I have seen pleople using this notation when assigning to lists as well , like : But I do n't really understand why they use [ : ] here . Is there a difference I do n't know ? | > > > a = [ 1,2,3,4 ] > > > b = a [ : ] > > > a [ 0 ] = 5 > > > print a [ 5 , 2 , 3 , 4 ] > > > print b [ 1 , 2 , 3 , 4 ] > > > a = [ 1,2,3,4 ] > > > b = [ 4,5,6,7 ] > > > a [ : ] = b > > > print a [ 4 , 5 , 6 , 7 ] > > > print b [ 4 , 5 , 6 , 7 ] | Assign value to a list using slice notation with assignee |
Python | Given the following models in a Django 2.2 app : I rely on Django 's lookup feature to filter on Item objects depending on some ShelfPosition fields : Item.objects.filter ( position__shelf_code= '' BF4 '' ) Is there any way I could implement a similar lookup functionality such as described above when using get_or_creat... | class ShelfPosition ( models.Model ) : shelf_code = models.CharField ( max_length=10 ) row = models.IntegerField ( ) column = models.IntegerField ( ) class Meta : constraints = [ models.UniqueConstraint ( fields= [ `` shelf_number '' , `` row '' , `` column '' ] , name= '' shelfpos_unique '' ) ] class Item ( models.Mod... | Django - Use model fields part in a create or update query |
Python | I have a mxn matrix A , where m % t = n % t = 0 , so that a smaller txt matrix B tiles the matrix without borders or overlaps . I want to check if A consists entirely of tiles from B without calculating a tiling as an intermediate step as efficiently as possible . Furthermore for my special use case , it is not necessa... | A = [ [ 1 , 0 , 1 , 0 ] , [ 0 , 1 , 0 , 1 ] , [ 1 , 0 , 1 , 0 ] , [ 0 , 1 , 0 , 1 ] ] B.shape = [ 2,2 ] -- > TrueB.shape = [ 1,1 ] -- > False import numpy as npx , y = B.shapex_a , y_a = A.shapex_t = x_a/xy_t = y_a/yB_dash = A [ : x , : y ] C = np.tile ( B_dash , ( x_t , y_t ) ) np.count_nonzero ( A-C ) | Count number of occurrences of an array without overlap in another array |
Python | Let 's assume I have a created a dict that is made up of n keys . Each key is mapped to a list of integers of a consistent length . What I want to make now is a new list that represents the sum of the integers at each point in lists of the dict . To illustrate : Expected output : As demonstrated above , I am not sure h... | my_dict = { ' a ' : [ 1 , 2 , 3 , 4 ] , ' b ' : [ 2 , 3 , 4 , 5 ] , ' c ' : [ 3 , 4 , 5 , 6 ] } total_sum_list = [ ] for key in my_dict.keys ( ) : total_sum_list += # # # some way of adding the numbers together total_sum_list = [ 6,9,12,15 ] | How to make a list of integers that is the sum of all the integers from a set of lists in a dict ? |
Python | Sorry for the messy title , I did n't know how to phrase this question well.Let 's say I have a table in which the first three columns are foo bar and baz . Then there are some number of arbitrary columns after . I want to manipulate the table such that these arbitrary columns are all collapsed under on column , called... | foo , bar , baz , 100 , 101 , 102 , 103 , 104,1 , 1 , 1 , 10 , 11 , 12 , 13 , 14,1 , 1 , 2 , 15 , 16 , 17 , 18 , 19,1 , 2 , 1 , 20 , 21 , 22 , 23 , 24 , num , foo , bar , baz , value,100 , 1 , 1 , 1 , 10,100 , 1 , 1 , 2 , 15,100 , 1 , 2 , 1 , 20,101 , 1 , 1 , 1 , 11,101 , 1 , 1 , 2 , 16,101 , 1 , 2 , 1 , 21,102 , 1 , 1... | How to { pivot|denormalize|manipulate } CSV table in Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.