lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I am given a list of dates in UTC , all hours cast to 00:00.I 'd like to determine if a ( lunar ) eclipse occurred in a given day ( ie past 24 hours ) Considering the python snippetI am assuming one is able to determine if an eclipse occurred within 24hrs of a time t byChecking that the first angle is close enough to 1... | from sykfield.api import loadeph = load ( 'de421.bsp ' ) def eclipticangle ( t ) : moon , earth = eph [ 'moon ' ] , eph [ 'earth ' ] e = earth.at ( t ) x , y , _ = e.observe ( moon ) .apparent ( ) .ecliptic_latlon ( ) return x.degrees | Determining lunar eclipse in skyfield |
Python | I have event data in the following format : Given a list of sequences S and events E , how can I efficiently find the non-overlapping occurrences of S in E that are within a time window W , and each event in the occurrence is within an interval L from the previous event ? Example results with S = { A , AA , AAA , AAB ,... | event A A A A A C B C D A A A Btimestamp 0 3 4 4 5 5 6 7 7 8 8 9 10 occurrences : A : [ 0 , 3 , 4 , 4 , 5 , 8 , 8 , 9 ] AA : [ ( 3,4 ) , ( 4,5 ) , ( 8,8 ) ] AAA : [ ( 3,4,4 ) , ( 8,8,9 ) ] AAB : [ ( 4,5,6 ) , ( 8,9,10 ) ] BB : [ ] CA : [ ( 7,8 ) ] | Find occurrences of subsequences in event data with time constraints |
Python | My initial dataframe is : and i would like to return the number of repetitions of each row as such : How can I count a pandas dataframe over duplications ? | Name Info1 Info20 Name1 Name1-Info1 Name1-Info21 Name1 Name1-Info1 Name1-Info22 Name1 Name1-Info1 Name1-Info23 Name2 Name2-Info1 Name2-Info24 Name2 Name2-Info1 Name2-Info2 Name Info1 Info2 Count0 Name1 Name1-Info1 Name1-Info2 31 Name2 Name2-Info1 Name2-Info2 2 | How can I count a pandas dataframe over duplications |
Python | New to python , trying to create a card deck and want to implement a printing method for print ( deck ) = > that gives a printed list of my cards . My class PlayingCard has a str method which works fine to print a single card.But when I create my Deck.cards object ( which is a list of PlayingCard objects ) , I ca n't s... | from enum import Enumclass Value ( Enum ) : Two = 2 Three = 3 Four = 4 Five = 5 Six = 6 Seven = 7 Eight = 8 Nine = 9 Ten = 10 Jack = 11 Queen = 12 King = 13 Ace = 14class Suit ( Enum ) : Spades = 1 Hearts = 2 Clubs = 3 Diamonds = 4class PlayingCard ( ) : def __init__ ( self , value , suit ) : self.value = value self.su... | __str__ method on list of objects |
Python | To solve my problem , I need to put together all possible arrays of length N , containing -1 , 0 and 1 , and run them through some function to see whether they meet a certain criterion . I have implemented 2 methods , a triadic numbers method and a recursion . They both return correct results , both check the same numb... | def triadicIteraction ( signsQty ) : signs = [ None for _ in range ( signsQty ) ] comb = int ( 3**signsQty-1 ) while ( comb > = 0 ) : combCopy = comb for n in range ( signsQty ) : signs [ n ] = 1-combCopy % 3 # [ 0,1,2 ] - > [ 1,0 , -1 ] , correct range for signs combCopy = combCopy//3 printIfTargetHit ( signs ) comb =... | Why is triadic iteration 2 times slower than the recursion ? |
Python | I have the following text : And the following ( broken ) regex : I want to match all # { words } but not the # # { words } ( Doubling ' # ' acts like escaping ) . Today I 've noticed that the regex I have is ignoring the first word ( refuses to match # { king } , but correctly ignores # # { day } and # # { fool } ) .An... | # { king } for a # # { day } , # # { fool } for a # { lifetime } [ ^ # ] # { [ a-z ] + } > > > regex = re.compile ( `` [ ^ # ] # { [ a-z ] + } '' ) > > > regex.findall ( string ) [ u ' # { lifetime } ' ] | Retrieve text inside # { } |
Python | I 'm working with a dictionary for an anagram program in Python . The keys are tuples of sorted letters , and the values are arrays of the possible words with those letters : I am using regex to filter the list down . So given r't $ ' as a filter the final result should be : So far I 've gotten it down to two steps . F... | wordlist = { ( 'd ' , ' g ' , ' o ' ) : [ 'dog ' , 'god ' ] , ( ' a ' , ' c ' , 't ' ) : [ 'act ' , 'cat ' ] , ( ' a ' , 's ' , 't ' ) : [ 'sat ' , 'tas ' ] , } filtered_list = { ( ' a ' , ' c ' , 't ' ) : [ 'act ' , 'cat ' ] , ( ' a ' , 's ' , 't ' ) : [ 'sat ' ] , } tmp = { k : [ w for w in v if re.search ( r't $ ' ,... | Paring Down a Dictionary of Lists in Python |
Python | I have a list of list consist of : I want to convert it into a list of list of tuple , like this : I read the data from a text file so this is my code : When I print standard_form_tokens it return only just one big list of tuple [ ( 'Di ' , 'in ' , 'QUE ' ) , ( 'mana ' , 'wh ' , 'QUE ' ) , ( 'lokasi ' , 'nn ' , 'INTENT... | > [ [ 'Di/in/QUE ' , 'mana/wh/QUE ' , 'lokasi/nn/INTENT ' , 'laboratorium/nnp/LOC ' , 'dasar/nnp/LOC ' , ' ? / ? /O ' ] , [ 'Di/in/QUE ' , 'mana/wh/QUE ' , 'lokasi/nn/INTENT ' , 'laboratorium/nnp/LOC ' , 'dasar/nnp/LOC ' , ' 2/nnp/LOC ' , ' ? / ? /O ' ] , [ 'Di/in/QUE ' , 'mana/wh/QUE ' , 'lokasi/nn/INTENT ' , 'laborat... | convert a list of list into a list of list of tuple |
Python | It is possible to map a dictionary key to a value that is a reference to amutable object , such as a list . Such a list object can be changed by invokinga list method on the reference , and the changes will be reflected in thedictionary . This is discussed in : Python : How do I pass a variable by reference ? and Pytho... | In [ 74 ] : x = { ' a ' : somelist } In [ 74 ] : x = { ' a ' : somelist [ : ] } In [ 77 ] : somelist.remove ( 'apples ' ) In [ 77 ] : x [ ' a ' ] .remove ( 'apples ' ) In [ 73 ] : somelist = [ 'apples ' , 'oranges ' , 'lemons ' , 'tangerines ' ] In [ 74 ] : x = { ' a ' : somelist } In [ 75 ] : xOut [ 75 ] : { ' a ' : [... | References to mutables ( e.g. , lists ) as values in Python dictionaries - what is best practice ? |
Python | So I have been trying to do this for a while now and am constantly coming up with differing failures . I need to take numerical input from the user and put it into a list and output it in decreasing value : So this worked well most of the time , ( I have been using the numbers 2,3,4 & 10 as input as I have been having ... | bids = [ ] bid = input ( 'Bid : ' ) while bid ! = `` : bids.append ( bid ) bid = input ( 'Bid : ' ) print ( 'The auction has finished ! The bids were : ' ) for bid in bids : bid = int ( bid ) for bid in reversed ( bids ) : print ( bid ) The auction has finished ! The bids were:243016 bids = [ ] bid = input ( 'Bid : ' )... | Reversing lists of numbers in python |
Python | I want a color gradient between black and red in matplotlib , where the low values are black and become more and more red with increasing Y-value . What do I have to change to get such a color gradient ? | import matplotlib.pyplot as pltxvals = np.arange ( 0 , 1 , 0.01 ) yvals = xvalsplt.plot ( xvals , yvals , `` r '' ) axes = plt.axes ( ) plt.show ( ) | matplotlib color gradient between two colors |
Python | Say I have a function that takes a value and a arbitrary number of functions , let 's call the function for chain_call.Without types a simple naive implementation would be : As you imagine , input_value could be anything really but it 's always the same as the first and only required argument of the first Callable in *... | def chain_call ( input_value , *args ) : for function in args : input_value = function ( input_value ) return input_value def chain_call ( input_value : Any , *args : List [ Callable [ Any ] , Any ] ) - > Any : ... T = TypeVar ( 'T ' ) def chain_call ( input_value : T , *args : List [ Callable [ T , ... ] , tr ] ) - > ... | Chained references in python type annotations |
Python | I have a numpy 2D array , and I would like to select different sized ranges of this array , depending on the column index . Here is the input array a = np.reshape ( np.array ( range ( 15 ) ) , ( 5 , 3 ) ) exampleThen , list b = [ 4,3,1 ] determines the different range sizes for each column slice , so that we would get ... | [ [ 0 1 2 ] [ 3 4 5 ] [ 6 7 8 ] [ 9 10 11 ] [ 12 13 14 ] ] [ 0 3 6 9 ] [ 1 4 7 ] [ 2 ] [ 0 3 6 9 1 4 7 2 ] slices = [ ] for i in range ( a.shape [ 1 ] ) : slices.append ( a [ : b [ i ] , i ] ) c = np.concatenate ( slices ) | Indexing different sized ranges in a 2D numpy array using a Pythonic vectorized code |
Python | I create a class named point as following : and create a list of point instances : Now I 'd like remove from the list the instance which x = 1 and y = 1 , how can I do this ? I try to add a __cmp__ method for class point as following : But the following code does not work | class point : def __init__ ( self ) : self.x = 0 self.y = 0 p1 = point ( ) p1.x = 1p1.y = 1p2 = point ( ) p2.x = 2p2.y = 2p_list = [ ] p_list.append ( p1 ) p_list.append ( p2 ) class point : def __init__ ( self ) : self.x = 0 self.y = 0 def __cmp__ ( self , p ) : return self.x==p.x and self.y==p.y r = point ( ) r.x = 1... | how to remove a object in a python list |
Python | The following list has some duplicated sublists , with elements in different order : How can I remove duplicates , retaining the first instance seen , to get : I tried to : Nevertheless , I do not know if this is the fastest way of doing it for large lists , and my attempt is not working as desired . Any idea of how to... | l1 = [ [ 'The ' , 'quick ' , 'brown ' , 'fox ' ] , [ 'hi ' , 'there ' ] , [ 'jumps ' , 'over ' , 'the ' , 'lazy ' , 'dog ' ] , [ 'there ' , 'hi ' ] , [ 'jumps ' , 'dog ' , 'over ' , 'lazy ' , 'the ' ] , ] l1 = [ [ 'The ' , 'quick ' , 'brown ' , 'fox ' ] , [ 'hi ' , 'there ' ] , [ 'jumps ' , 'over ' , 'the ' , 'lazy ' ,... | Efficiently remove duplicates , order-agnostic , from list of lists |
Python | I am using a class instance which returns a string . I am calling twice this instance and collecting returned values into a list . Then am trying to use .sort ( ) to sort these two strings . However , when I do so it throws an error saying that the type is ( Nonetype - considers it as object ) . I did check with type (... | list_of_strings = [ class_method ( args ) , class_method ( another_args ) ] # # this instance returns stringprint type ( list_of_strings [ 0 ] ) # prints type 'str ' list_sorted = list ( list_of_strings.sort ( ) ) TypeError : 'NoneType ' object is not iterable | Why string returned from a class instance keeps NoneType type even though IDLE says it is a string ? |
Python | I am aware of Python 's ternary operator : But what if a and b are the same thing ? Let me exemplify it : In a first attempt , tasksLeft ( ) would evaluate to True , so the ternary operator would evaluate to [ `` bar '' , ] .In a second attempt , tasksLeft ( ) would evaluate to False ( [ ] ) , so it would evaluate to t... | result = a if b else c tasks = [ `` foo '' , `` bar '' ] def tasksLeft ( ) : return taskstasks.remove ( 'foo ' ) my_tasks = tasksLeft ( ) if tasksLeft ( ) else 'no tasks left ' tasks.remove ( 'bar ' ) my_tasks = tasksLeft ( ) if tasksLeft ( ) else 'no tasks left ' if not my_tasks = tasksLeft ( ) : my_tasks = 'no tasks ... | Evaluate variable assignment |
Python | I want to print out a sentence inside of a for loop where a different iteration of the sentence prints out for each different situation i.e . I have two different lists : student_result_reading and student_nameHere are my two issues : When I enter 2 or more names , they are not formatted correctly.When I enter 1 name ,... | student_result_reading = [ ] student_name = [ ] while True : student_name_enter = input ( `` Please enter student name : `` ) student_name.append ( student_name_enter ) student_enter = int ( input ( `` Please enter student result between 0 - 100 % : `` ) ) student_result_reading.append ( student_enter ) continueask = i... | How do I use one 'for loop ' for 2 different lists |
Python | I expanded and added as a new question.I have a list : Then I recognize which value occurs most often , which value I retain in the variable i2 : Later all values that repeat are increased by 10 , but in addition to the maximum values . This is the code that I use : After this operation I get : As you can see , the mos... | li = [ 2 , 3 , 1 , 4 , 2 , 2 , 2 , 3 , 1 , 3 , 2 ] f = { } for item in li : f [ item ] = f.get ( item , 0 ) + 1 for i in f : if f [ i ] ==int ( max ( f.values ( ) ) ) : i2 = i for i in range ( len ( li ) ) : for x in range ( i + 1 , len ( li ) ) : if li [ i ] == li [ x ] and li [ i ] ! = i2 : li [ x ] = li [ x ] + 10 l... | Finding duplicates in list and operating only on one of them |
Python | I ’ m having trouble with exiting the following while loop . This is a simple program that prints hello if random value is greater than 5 . The program runs fine once but when I try to run it again it goes into an infinite loop . | from random import * seed ( ) a = randint ( 0,10 ) b = randint ( 0,10 ) c = randint ( 0,10 ) count = 0 while True : if a > 5 : print ( `` aHello '' ) count = count + 1 else : a = randint ( 0,10 ) if b > 5 : print ( `` bHello '' ) count = count + 1 else : b = randint ( 0,10 ) if c > 5 : print ( `` cHello '' ) count = co... | How do I exit this while loop ? |
Python | I 'm trying to ascertain how I can create a column that indicates in advance ( X rows ) when the next occurrence of a value in another column will occur with pandas that in essence performs the following functionality ( In this instance X = 3 ) : dfApart from doing a iterative/recursive loop through every row : However... | rowid event indicator1 True 1 # Event occurs2 False 03 False 04 False 1 # Starts indicator5 False 16 True 1 # Event occurs7 False 0 i = df.index [ df [ 'event ' ] ==True ] dfx = [ df.index [ z-X : z ] for z in i ] df [ 'indicator ' ] [ dfx ] =1df [ 'indicator ' ] .fillna ( 0 ) | Pandas : How to create a column that indicates when a value is present in another column a set number of rows in advance ? |
Python | I want to count the existing routes of the given maze . ( anyway , the problem itself is not that important ) Problem is , I tried to count the number of cases that fit the conditions within the recursive functions.These are two conditions that have to be counted.I tried counting the conditions like thisBut since I 'm ... | def calcPath ( trace_map , x , y ) : n = len ( trace_map ) count = 0 if x > n - 1 or y > n - 1 : pass elif x < n and y < n : if x + trace_map [ x ] [ y ] == ( n - 1 ) and y == ( n - 1 ) : count += 1 elif x == ( n - 1 ) and y + trace_map [ x ] [ y ] == ( n - 1 ) : count += 1 else : calcPath ( trace_map , x + trace_map [... | How can I count the number of cases in recursive functions ? |
Python | I 've been trying to plot the Bates distribution curve , The Bates distribution is the distribution of the mean of n independent standard uniform variates ( from 0 to 1 ) . ( I worked on the interval [ -1 ; 1 ] , I made a simple change of variable ) .The curve destabilizes after such number of n , which prevents me fro... | samples=10**6def combinaison ( n , k ) : # combination of K out of N cnk=fac ( n ) / ( fac ( k ) *fac ( abs ( n-k ) ) ) # fac is factoriel return cnkdef dens_probas ( a , b , n ) : x=np.linspace ( a , b , num=samples ) y= ( x-a ) / ( b-a ) F=list ( ) for i in range ( 0 , len ( y ) ) : g=0 for k in range ( 0 , int ( n*y... | Implementing Bates distribution |
Python | __repr__ is used to return a string representation of an object , but in Python a function is also an object itself , and can have attributes.How do I set the __repr__ of a function ? I see here that an attribute can be set for a function outside the function , but typically one sets a __repr__ within the object defini... | retry_mysql_exception_types = ( InterfaceError , OperationalError , TimeoutError , ConnectionResetError ) def return_last_retry_outcome ( retry_state ) : `` '' '' return the result of the last call attempt '' '' '' return retry_state.outcome.result ( ) def my_before_sleep ( retry_state ) : print ( `` Retrying { } : att... | How to set a repr for a function itself ? |
Python | I have a list of items with properties `` Type '' and `` Time '' that I want to quickly sum the time for each `` Type '' and append to another list . The list looks like this : I want to do something that works like this : With Travel_Times finally looking like this : This seems like something that should be easy to do... | Items = [ { 'Name ' : A , 'Type ' : 'Run ' , 'Time ' : 5 } , { 'Name ' : B , 'Type ' : 'Walk ' , 'Time ' : 15 } , { 'Name ' : C , 'Type ' : 'Drive ' , 'Time ' : 2 } , { 'Name ' : D , 'Type ' : 'Walk ' , 'Time ' : 17 } , { 'Name ' : E , 'Type ' : 'Run ' , 'Time ' : 5 } ] Travel_Times= [ ( `` Time_Running '' , '' Time_Wa... | Efficiently sum items by type |
Python | this has been irking me for years.given I have a list of words : even though it 's super lightweight , I still feel weird writing this list comprehension : i do n't like applying strip ( ) twice . it just seems silly . it 's slightly/negligibly faster like this : which is also the same asI 'm wondering if there are oth... | words = [ 'one ' , 'two ' , 'three ' , `` , ' four ' , 'five ' , 'six ' , \ 'seven ' , 'eight ' , ' nine ' , 'ten ' , `` ] cleaned = [ i.strip ( ) for i in words if i.strip ( ) ] _words = [ w.strip ( ) for w in words ] cleaned = [ w for w in _words if w ] cleaned = [ i for i in [ w.strip ( ) for w in words ] if i ] | Python - are there other ways to apply a function and filter in a list comprehension ? |
Python | According to this answer , a class object cls can be replicated withThis works perfectly for most normal cases . It does not work when the metaclass of cls is not type . My initial naive fix was to doHowever , this is simply pointless . There is no way to know what a metaclass does , as this answer to a related questio... | cls_copy = type ( 'cls_copy ' , cls.__bases__ , dict ( cls.__dict__ ) ) cls_copy = type ( cls ) ( 'cls_copy ' , cls.__bases__ , dict ( cls.__dict__ ) ) cls_copy = type ( 'cls_copy ' , cls.__bases__ , dict ( cls.__dict__ ) , metaclass=type ( cls ) ) TypeError : __init_subclass__ ( ) takes no keyword arguments | Is it possible to properly copy a class using type |
Python | Can somebody explain this non-monotonic memory usage of a dictionary in CPython 2.7 ? Python3 is reasonable here , it prints the size of { 'one ' : 1 , 'two ' : 2 , 'three ' : 3 , 'four ' : 4 , 'five ' : 5 , 'six ' : 6 , 'seven ' : 7 } as 480 . I tried this on Ubuntu 15.10 and OS X 10.11 . | > > > import sys > > > sys.getsizeof ( { } ) 280 > > > sys.getsizeof ( { 'one ' : 1 , 'two ' : 2 , 'three ' : 3 , 'four ' : 4 , 'five ' : 5 } ) 280 > > > sys.getsizeof ( { 'one ' : 1 , 'two ' : 2 , 'three ' : 3 , 'four ' : 4 , 'five ' : 5 , 'six ' : 6 } ) 1048 > > > sys.getsizeof ( { 'one ' : 1 , 'two ' : 2 , 'three ' ... | Non-monotonic memory consumption in Python2 dictionaries |
Python | I have a Python script that needs to look for a certain file.I could use os.path.isafile ( ) , but I 've heard that 's bad Python , so I 'm trying to catch the exception instead.However , there 's two locations I could possibly look for the file . I could use nested trys to handle this : Or I could just put a pass in t... | try : keyfile = 'location1 ' try_to_connect ( keyfile ) except IOError : try : keyfile = 'location2 ' try_to_connect ( keyfile ) except : logger.error ( 'Keyfile not found at either location1 or location2 ' ) try : keyfile = 'location1 ' try_to_connect ( keyfile ) except IOError : passtry : keyfile = 'location2 ' try_t... | Pythonic way of handling multiple possible file locations ? ( Without using nested trys ) |
Python | Notice the two parameters in the first line of the docstring.When would you pass two arguments to len ? Is the docstring incorrect ? I 'm using Python 3.4.0 . | > > > print ( len.__doc__ ) len ( module , object ) Return the number of items of a sequence or mapping. > > > len ( os , 1 ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > TypeError : len ( ) takes exactly one argument ( 2 given ) | What is `` module '' in the docstring of len ? |
Python | Very basic question : in my python 2.7 code I have situation roughly as follows : the code runs in python / spyder ( 64bit ) , but fails in Cython , because of a float division by 0 . The printed number is 0 . When I define the division is fine and the printed number , too . What is the error ? | b=5.0*10** ( -9 ) a=9print ( a ) c=a/ ( 1.0*b ) b=0.000000005 | Operation 10** ( -9 ) correct in python , but wrong in Cython |
Python | To iterate a file by lines , one can do - ( where f is the file iterator ) .I want to iterate the file by blocks delimited by commas , instead of blocks delimited by newlines . I can read all lines and then split the string on commas , but whats the pythonic way to do this ? | for line in f : | Pythonic way to iterate through a file on something other than newlines |
Python | I want to pick out some items in one rectangular box with axis limits of ( xmin , xmax , ymin , ymax , zmin , zmax ) . So i use the following conditions , But I think python has some concise way to express it . Does anyone can tell me ? | if not ( ( xi > = xmin and xi < = xmax ) and ( yi > = ymin and yi < = ymax ) and ( zi > = zmin and zi < = zmax ) ) : expression | Simplification of if multiple conditions in python |
Python | Evening Chaps , hopefully , this question is better than my first one earlier this year which got -7 ! ( of which I was actually grateful as it helped highlight my ignorance ) What I 'm trying to achieve is to write a cunning line of code , that I can call in any dataframe I work in to get the correct week number or da... | import pandas as pdimport numpy as npdays = pd.date_range ( '01/01/2018 ' , '01/04/2019 ' , freq='D ' ) df = pd.DataFrame ( { 'Date ' : days } ) print ( df.head ( 5 ) ) Date0 2018-01-011 2018-01-022 2018-01-033 2018-01-044 2018-01-05 df [ 'Week ' ] = np.where ( df [ 'Date ' ] .dt.month > = 4 , ( df [ 'Date ' ] + pd.Tim... | Attempting to write a few lines of code to create a master date lookup table |
Python | I 'm attempting to create a function that keeps count of the times it has been called , and I want the information to stay inside the function itself.I tried creating a wrapper like so : I thought it 'd work , but I got an AttributeError saying 'function ' object has no attribute 'count'.I already figured the problem :... | def keep_count ( f ) : f.count = 0 @ functools.wraps ( f ) def wrapped_f ( *args , **kwargs ) : f ( *args , **kwargs ) f.count += 1 return wrapped_f @ keep_countdef test_f ( *args , **kwargs ) : print ( args , kwargs ) | Change an attribute of a function inside its own body ? |
Python | So I have a dataframe ( or series ) where there are always 4 occurrences of each of column ' A ' , like this : I also have another dataframe , with values like the ones found in column A , but they do n't always have 4 values . They also have more columns , like this : I wanted to merge them such they end up like this ... | df = pd.DataFrame ( [ [ 'foo ' ] , [ 'foo ' ] , [ 'foo ' ] , [ 'foo ' ] , [ 'bar ' ] , [ 'bar ' ] , [ 'bar ' ] , [ 'bar ' ] ] , columns= [ ' A ' ] ) A0 foo1 foo2 foo3 foo4 bar5 bar6 bar7 bar df_key = pd.DataFrame ( [ [ 'foo ' , 1 , 2 ] , [ 'foo ' , 3 , 4 ] , [ 'bar ' , 5 , 9 ] , [ 'bar ' , 2 , 4 ] , [ 'bar ' , 1 , 9 ] ... | Merge items on dataframes with duplicate values |
Python | What does this line of code mean , from tornado ? I understand these assignments : list [ index ] = val , list [ index1 : index2 ] = list2 , but I 've never seen that from Tornado . | [ sock ] = netutil.bind_sockets ( None , 'localhost ' , family=socket.AF_INET ) | what does [ sock ] = func ( ) mean ? |
Python | Hi I have a two tables like this.source table target table : I need output as follows1 ) I need to match ( source ( orig1 orig2 orig3 ) == target ( orig1 orig2 orig3 ) ) , if its macthing we need to append from source to target table by increment the version by 1 if its not matching , just append version as ' 0'expecte... | orig1 orig2 orig3 xref1 xref2 xref31 1 1 2 2 21 1 1 3 3 323 23 23 12 12 12 orig1 orig2 orig3 xref1 xref2 xref3 version1 1 1 1 1 1 0 orig1 orig2 orig3 xref1 xref2 xref3 version1 1 1 1 1 1 01 1 1 2 2 2 11 1 1 3 3 3 223 23 23 12 12 12 0 val source = spark.sql ( `` select xref1 , xref2 , xref3 , orig1 , orig2 , orig3 from ... | row level comparison of two tables |
Python | The grammar for del statement : It allows deleting starred expressions . So , the parser does n't mind this , even though it would be causing SyntaxError : ca n't use starred expression here at runtime : Is there some usage I 'm missing which can have a starred delete target ? Should n't it be instead the simpler gramm... | del_stmt : 'del ' ( expr|star_expr ) ( ' , ' ( expr|star_expr ) ) * [ ' , ' ] > > > ast.parse ( `` del *a '' ) < _ast.Module at 0xcafef00d > > > > ast.dump ( compile ( 'del *a ' , filename='wtf.py ' , mode='single ' , flags=ast.PyCF_ONLY_AST ) ) '' Interactive ( body= [ Delete ( targets= [ Starred ( value=Name ( id= ' ... | del *a : ca n't use starred expression here |
Python | SetupConsider the numpy array aQuestionFor each column , I want to determine the cumulative equivalent for all.The result should look like this : Take the first columnSo basically , cumulative all is True as long as we have True and turns False from then on at the first FalseWhat I have triedI can get the result withBu... | > > > np.random.seed ( [ 3,1415 ] ) > > > a = np.random.choice ( [ True , False ] , ( 4 , 8 ) ) > > > aarray ( [ [ True , False , True , False , True , True , False , True ] , [ False , False , False , False , True , False , False , True ] , [ False , True , True , True , True , True , True , True ] , [ True , True , T... | How to do a cumulative `` all '' |
Python | Imagine you have published two pre-releases : My install_requires section in setup.py states : Now , when i run pip install . -- upgrade -- pre I get an error : ERROR : Could not find a version that satisfies the requirement package < 1.0.0 , > =0.0.2 ( from versions : 0.0.1.dev0 , 0.0.2.dev0 ) ERROR : No matching dist... | package 0.0.1.dev0 package 0.0.2.dev0 [ 'package > =0.0.2 , < 1.0.0 ' ] | Pre-release versions are not matched by pip when using the ` -- pre ` option |
Python | This is a Find All Numbers Disappeared in an Array problem from LeetCode : Given an array of integers where 1 ≤ a [ i ] ≤ n ( n = size of array ) , some elements appear twice and others appear once.Find all the elements of [ 1 , n ] inclusive that do not appear in this array.Could you do it without extra space and in O... | Input : [ 4,3,2,7,8,2,3,1 ] Output : [ 5,6 ] def findDisappearedNumbers ( self , nums : List [ int ] ) - > List [ int ] : results_list= [ ] for i in range ( 1 , len ( nums ) +1 ) : if i not in nums : results_list.append ( i ) return results_list | Find missing elements in a list created from a sequence of consecutive integers with duplicates in O ( n ) |
Python | I 'm trying to run a python script hello.py from within an Android Process.Here are the steps I 've followed : I have procured python binaries and need linked libraries . I have tested them and they are working in the terminal emulator . I have added them to my asset folder and copied them to the privatestorage and mad... | 07-19 13:35:15.391 26991-26991/com.vibhinna.example I/System.out : Here is the standard output of the command:07-19 13:35:32.001 26991-26991/com.vibhinna.example I/System.out : Here is the standard error of the command ( if any ) :07-19 13:35:32.001 26991-26991/com.vibhinna.example I/System.out : Fatal Python error : P... | Running hello.py from within an Android Process |
Python | If I have a pandas data frame like this made up of 0 and 1s : How do I filter out outliers such that I get something like this : Such that I remove the outliers . | 1 1 1 0 0 0 0 1 0 1 1 1 1 1 0 0 0 0 1 1 1 0 0 0 0 1 0 1 0 0 0 0 1 0 0 0 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 | How do you remove values not in a cluster using a pandas data frame ? |
Python | I was looking around list comprehension and saw smth strange.Code : Result : [ ( 0 , ' a ' ) , ' b ' , ( 0 , 'd ' ) , ( 0 , ' c ' ) ] But I wanted to see : [ ( 3 , ' a ' ) , ' b ' , ( 2 , 'd ' ) , ( 3 , ' c ' ) ] What 's the cause of such behaviour ? | a = [ ' a ' , ' a ' , ' a ' , ' b ' , 'd ' , 'd ' , ' c ' , ' c ' , ' c ' ] print [ ( len ( list ( g ) ) , k ) if len ( list ( g ) ) > 1 else k for k , g in groupby ( a ) ] | python 2 strange list comprehension behaviour |
Python | I need to compute AB⁻¹ in Python / Numpy for two matrices A and B ( B being square , of course ) .I know that np.linalg.inv ( ) would allow me to compute B⁻¹ , which I can then multiply with A.I also know that B⁻¹A is actually better computed with np.linalg.solve ( ) .Inspired by that , I decided to rewrite AB⁻¹ in ter... | np.linalg.solve ( a.transpose ( ) , b.transpose ( ) ) .transpose ( ) import numpy as npn , m = 4 , 2np.random.seed ( 0 ) a = np.random.random ( ( n , n ) ) b = np.random.random ( ( m , n ) ) print ( np.matmul ( b , np.linalg.inv ( a ) ) ) # [ [ 2.87169378 -0.04207382 -1.10553758 -0.83200471 ] # [ -1.08733434 1.00110176... | Computing ` AB⁻¹ ` with ` np.linalg.solve ( ) ` |
Python | I use data from a past kaggle challenge based on panel data across a number of stores and a period spanning 2.5 years . Each observation includes the number of customers for a given store-date . For each store-date , my objective is to compute the average number of customers that visited this store during the past 60 d... | pd.DataFrame ( { 'Store ' : { 0 : 1 , 1 : 1 , 2 : 1 , 3 : 1 , 4 : 1 } , 'Customers ' : { 0 : 668 , 1 : 578 , 2 : 619 , 3 : 635 , 4 : 785 } , 'Date ' : { 0 : pd.Timestamp ( '2013-01-02 00:00:00 ' ) , 1 : pd.Timestamp ( '2013-01-03 00:00:00 ' ) , 2 : pd.Timestamp ( '2013-01-04 00:00:00 ' ) , 3 : pd.Timestamp ( '2013-01-0... | Speeding up past-60-day mean in pandas |
Python | In Python 2.x , I 'd write ... ... to get integers from 0 to 4 printed in the same row . How to do that in Python 3.x , since print is a function now ? | for i in range ( 5 ) : print i , | Output being printed in the same line , Py3k |
Python | I am working with a dataframe that looks like this.What is an efficient way find the minimum values for 'time ' by id , then set 'diff ' to nan at those minimum values . I am looking for a solution that results in : | id time diff0 0 34 nan1 0 36 22 1 43 73 1 55 124 1 59 45 2 2 -576 2 10 8 id time diff0 0 34 nan1 0 36 22 1 43 nan3 1 55 124 1 59 45 2 2 nan6 2 10 8 | Iterate through the rows of a dataframe and reassign minimum values by group |
Python | I 'm asking this question in a more broad spectrum because I 'm not facing this specific issue right now , but I 'm wondering how to do it in the future.If I have a long running python script , that is supposed to do something all the time ( could be a infine loop , if that helps ) . The code is started by running pyth... | import time , csvimport GenericAPIclass GenericDataCollector : def __init__ ( self ) : self.generic_api = GenericAPI ( ) def collect_data ( self ) : while True : # Maybe this could be a var that is changed from outside of the class ? data = self.generic_api.fetch_data ( ) # Returns a JSON with some data self.write_on_c... | How to make my code stopable ? ( Not killing/interrupting ) |
Python | I have a dictionary of lists : I may have more than two key/value pairs . I want to create a list of dictionaries which gives me all the possible combinations of the the lists corresponding to a and b : e.g.I can do this by hard coding the keys : But I do n't want to hard code as I do n't know how many key/value pairs ... | In [ 72 ] : paramsOut [ 72 ] : { ' a ' : [ 1 , 2 , 3 ] , ' b ' : [ 5 , 6 , 7 , 8 ] } [ { ' a':1 , ' b'=5 } , { ' a':1 , ' b'=6 } , { ' a':1 , ' b'=7 } , ... { ' a':3 , ' b'=8 } , ] for a , b in itertools.product ( *p.itervalues ( ) ) : print { ' a ' : a , ' b ' : b } | Dictionary of lists to Dictionary |
Python | Someone just showed me this weird example of python syntax . Why is [ 4 ] working ? I would have expected it to evaluate to either [ 5 ] or [ 6 ] , neither of which works . Is there some premature optimisation going on here which should n't be ? | In [ 1 ] : s = 'abcd'In [ 2 ] : c = ' b'In [ 3 ] : c in s Out [ 3 ] : TrueIn [ 4 ] : c == c in sOut [ 4 ] : TrueIn [ 5 ] : True in s -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -TypeError Traceback ( most recent call last ) < ipython-input-5-e0014934569... | What 's going on with this python syntax ? ( c == c in s ) |
Python | I want to know how __future__ imports interact with eval and exec ( and compile , I guess ) .Experimentation ( with python 2 ) shows that module-level __future__ imports do have an effect on code executed by eval and exec : Output : But at the same time , code executed with exec can perform its own __future__ imports t... | from __future__ import print_functionprint ( 1 , end= ' ! \n ' ) eval ( r '' print ( 2 , end= ' ! \n ' ) '' ) exec r '' print ( 3 , end= ' ! \n ' ) '' 1 ! 2 ! 3 ! print 1exec r '' from __future__ import print_function ; print ( 2 , end= ' ! \n ' ) '' print 3exec r '' print 4 '' 12 ! 34 | How exactly do eval and exec interact with __future__ ? |
Python | Comming from a Java background , when developing services connected by JMS I used to process messages and distinguish them by checking their type , e.g ( simplified ) : So now I am building a messaging front-end for some Python modules in RabbitMQ ( topic communication ) . I am planing on using one queue for each consu... | Object object = myQueue.consume ( ) ; if ( object instanceof MessageA ) { processMessageA ( ( MessageA ) object ) } else if ( object instanceof MessageB ) { processMessageB ( ( MessageB ) object ) } ... | What is the most Pythonic way of processing messages like this Java `` instance-filtering '' [ RabbitMQ ] |
Python | Is there a more pythonic way of doing the following : where it is iterable , fun is a function that takes two inputs and returns two outputs , and val is an initial value that gets `` transformed '' by each call to fun ? I am asking because I use map , zip , filter , reduce and list-comprehension on a regular basis , b... | def mysteryFunction ( it , fun , val ) : out = [ ] for x in it : y , val = fun ( x , val ) out.append ( y ) return out , val fac = ( 365*24*3600 , 7*24*3600 , 24*3600 , 3600 , 60 , 1 ) dur , rem = mysteryFunction ( fac , lambda x , y : divmod ( y , x ) , 234567 ) | Pythonic cumulative map |
Python | I am quite confused with the behaviour as shown below : Can someone please explain ? | > > > ( -7 ) % 3 2 > > > Decimal ( '-7 ' ) % Decimal ( ' 3 ' ) Decimal ( '-1 ' ) > > > > > > ( -7 ) // 3-3 > > > Decimal ( '-7 ' ) // Decimal ( ' 3 ' ) Decimal ( '-2 ' ) > > > | Different result of modulo and integer divison for float and Decimal |
Python | The following code works in Python 2.7 , to dynamically inject local variables into a function scope : It 's a bit subtle , but the presence of an exec statement indicates to the compiler that the local namespace may be modified . In the reference implementation , it will transform the lookup of the name `` locals '' f... | myvars = { `` var '' : 123 } def func ( ) : exec ( `` '' ) locals ( ) .update ( myvars ) print ( var ) func ( ) # assert `` var '' not in globals ( ) | How to convert this Python 2.7 code to Python 3 ? |
Python | I would like to know why this code prints 4 instead of 3 . Where is the fourth reference ? | import sysdef f ( a ) : print ( sys.getrefcount ( a ) ) a = [ 1 , 2 , 3 ] f ( a ) | sys.getrefcount ( ) prints one more than the expected number of references to an object ? |
Python | I am trying to implement the NIMA Research paper by Google where they rate the image quality . I am using the TID2013 data set . I have 3000 images each one having a score from 0.00 to 9.00I FOUND the code for loss function given belowand I wrote the code for model building as : PROBLEM : When I use ImageDataGenerator ... | df.head ( ) > > Image Name Score0 I01_01_1.bmp 5.514291 i01_01_2.bmp 5.567572 i01_01_3.bmp 4.944443 i01_01_4.bmp 4.378384 i01_01_5.bmp 3.86486 def earth_mover_loss ( y_true , y_pred ) : cdf_true = K.cumsum ( y_true , axis=-1 ) cdf_pred = K.cumsum ( y_pred , axis=-1 ) emd = K.sqrt ( K.mean ( K.square ( cdf_true - cdf_pr... | What should be the Input types for Earth Mover Loss when images are rated in decimals from 0 to 9 ( Keras , Tensorflow ) |
Python | Friends , I am analyzing some texts . My requirement is to gecode the address written in English letters of a different native language.In above sentence words like , `` ke paas '' -- > is a HINDI word ( Indian national language ) , which means `` near '' in English and `` chandapur market '' is a noun ( can be ignored... | Ex : chandpur market ke paas , village gorthaniya , UP , INDIA | Geocode the address written in native language using English letters |
Python | I have been working on this function that generates some parameters I need for a simulation code I am developing and have hit a wall with enhancing its performance.Profiling the code shows that this is the main bottleneck so any enhancements I can make to it however minor would be great.I wanted to try to vectorize par... | import numpy as npfrom scipy.sparse import linalg as LAdef get_params ( num_bonds , energies ) : `` '' '' Returns the interaction parameters of different pairs of atoms . Parameters -- -- -- -- -- num_bonds : ndarray , shape = ( M , 20 ) Sparse array containing the number of nearest neighbor bonds for different pairs o... | Can this python function be vectorized ? |
Python | I see frequent pandas examples on SO using time series that have spaces within the timestamps : Or this where the times are n't part of the index : Is there a good way to copy these ( or similar ) data back into Python to work with ? I have found posts like this and this which were lifesavers for getting many examples ... | A2020-01-01 09:20:00 02020-01-01 09:21:00 12020-01-01 09:22:00 22020-01-01 09:23:00 32020-01-01 09:24:00 4 dates values cat0 2020-01-01 09:20:00 0.758513 a1 2020-01-01 09:21:00 0.337325 b2 2020-01-01 09:22:00 0.618372 b3 2020-01-01 09:23:00 0.878714 b4 2020-01-01 09:24:00 0.311069 b # oneimport pandas as pdimport numpy... | How can I copy DataFrames with datetimes from Stack Overflow into Python ? |
Python | I am new to python and one of the things every newbie do come across is the slice operator . I have a list : As per my understanding calling li [ : -1 ] is same as calling li [ 0 : -1 ] and it is but when using it with a negative steps things do not work exactly as I thought they would . So getting to my question why t... | li= [ 1,2,3,4,5,6,7 ] print ( li [ : -3 : -2 ] ) # is 7 print ( li [ 0 : -3 : -2 ] ) # is [ ] | Negative Bounds for Slice Operator |
Python | Consider the dataframe dfIf I shift along axis=0 ( the default ) It pushes all rows downwards one row as expected.But when I shift along axis=1Everything is null when I expectedI understand why this happened . For axis=0 , Pandas is operating column by column where each column is a single dtype and when shifting , ther... | df = pd.DataFrame ( dict ( A= [ 1 , 2 ] , B= [ ' X ' , ' Y ' ] ) ) df A B0 1 X1 2 Y df.shift ( ) A B0 NaN NaN1 1.0 X df.shift ( axis=1 ) A B0 NaN NaN1 NaN NaN A B0 NaN 11 NaN 2 df = pd.DataFrame ( dict ( A= [ 1 , 2 ] , B= [ 1. , 2 . ] ) ) df A B0 1 1.01 2 2.0 df.shift ( axis=1 ) A B0 NaN NaN1 NaN NaN df_shifted A B0 Na... | dtypes muck things up when shifting on axis one ( columns ) |
Python | for example if i have : and i want to check if the following list is the same as one of the lists that the array consist of : I triedBut the following also returns True , which should be false : | import numpy as npA = np.array ( [ [ 2,3,4 ] , [ 5,6,7 ] ] ) B = [ 2,3,4 ] B in A # which returns True B = [ 2,2,2 ] B in A | How can i check that a list is in my array in python |
Python | I have a data frame that look as follow : PrintingMy desired output is something like thisThat is , I 'm searching for a way to change the 'decil ' column from long to wide format while at the same time changing the year columns from wide to long format . I have tried pd.pivot_table , loops and unstack without any luck... | import pandas as pdd = { 'decil ' : [ ' 1 . decil ' , ' 1 . decil ' , ' 2 . decil ' , ' 2 . decil ' , ' 3 . decil ' , ' 3 . decil ' ] , 'kommune ' : [ 'AA ' , 'BB ' , 'AA ' , 'BB ' , 'AA ' , 'BB ' ] , '2010 ' : [ 44,25,242,423,845,962 ] , '2011 ' : [ 64,26,239,620,862,862 ] } df = pd.DataFrame ( data=d ) decil kommune ... | Long/wide data to wide/long |
Python | So first ... my directory structure..Now , execute.py calls both foo and bar .py asI am trying to run this as : But I am getting this import errorWhat am I missing ( note that there is no init inside script folder ? ? ) ? Thanks | -- -script/execute.py | L -- -helper -- -foo.py L -- -- -bar.py L -- - __init__.py from helper.foo import some_func python script/execute.py from helper.foo import some_func Import error : No module named helper ? ? | Not able to import module |
Python | I am building a project that requires the data to be shared globally . I built a class GlobalDataBase to handle these data , which is like the way in How do I avoid having class data shared among instances ? and https : //docs.python.org/2/tutorial/classes.html . However , I found something a little bit weird to me . M... | class GlobalDataBase : a = [ ] def copy_to_a ( self , value ) : self.a = value def assign_to_a ( self , value ) : for idx in range ( 0 , len ( value ) ) : self.a.append ( value [ idx ] ) def test_copy ( ) : gb1 = GlobalDataBase ( ) gb1.copy_to_a ( [ 1,2 ] ) print gb1.a gb2 = GlobalDataBase ( ) print gb2.adef test_assig... | Share global data in Python |
Python | I have been trying to understand __new__ and metaprogramming . So I had a look at official python source code.http : //hg.python.org/cpython/file/2.7/Lib/fractions.pyTheir __new__ function for Fractions looks like : Why do they return self , rather thanI thought I understood it , but now I 'm confused . ( Edit ) To sup... | class Fraction ( Rational ) : def __new__ ( cls , numerator=0 , denominator=None ) : `` '' '' Constructs a Fraction . ... `` '' '' self = super ( Fraction , cls ) .__new__ ( cls ) ... if isinstance ( numerator , float ) : # Exact conversion from float value = Fraction.from_float ( numerator ) self._numerator = value._n... | __new__ in fractions module |
Python | I am running into an issue with subtyping the str class because of the str.__call__ behavior I apparently do not understand . This is best illustrated by the simplified code below.I always thought the str ( obj ) function simply calls the obj.__str__ method , and that 's it . But for some reason it also calls the __ini... | class S ( str ) : def __init__ ( self , s : str ) : assert isinstance ( s , str ) print ( s ) class C : def __init__ ( self , s : str ) : self.s = S ( s ) def __str__ ( self ) : return self.sc = C ( `` a '' ) # - > prints `` a '' c.__str__ ( ) # - > does not print `` a '' str ( c ) # - > asserts fails in debug mode , e... | Unexpected behavior of python builtin str function |
Python | I want to make a numpy array that contains how many times a value ( between 1-3 ) occurs at a specific location . For example , if I have : I want to get back an array like so : Where the array tells me that 1 occurs once in the first position , 2 occurs once in the second position , 3 occurs once in the third position... | a = np.array ( [ [ 1,2,3 ] , [ 3,2,1 ] , [ 2,1,3 ] , [ 1,1,1 ] ] ) [ [ [ 1 0 0 ] [ 0 1 0 ] [ 0 0 1 ] ] [ [ 0 0 1 ] [ 0 1 0 ] [ 1 0 0 ] ] [ [ 0 1 0 ] [ 1 0 0 ] [ 0 0 1 ] ] [ [ 1 0 0 ] [ 1 0 0 ] [ 1 0 0 ] ] ] a = np.array ( [ [ 1,2,3 ] , [ 3,2,1 ] , [ 2,1,3 ] , [ 1,1,1 ] ] ) cumulative = np.zeros ( ( 4,3,3 ) ) for r in r... | One line solution for editing a numpy array of counts ? ( python ) |
Python | I am a fairly comfortable PHP programmer , and have very little Python experience . I am trying to help a buddy with his project , the code is easy enough to write in Php , I have most of it ported over , but need a bit of help completing the translation if possible.The target is to : Generate a list of basic objects w... | < ? phpsrand ( 3234 ) ; class Object { // Basic item description public $ x =null ; public $ y =null ; public $ name =null ; public $ uid =null ; } class Trace { // Used to update status or move position # public $ x =null ; # public $ y =null ; # public $ floor =null ; public $ display =null ; // Currently all we care... | Making the leap from PhP to Python |
Python | I am trying since a couple of months to be able to generate images of PCB gerbers using an online service , and thinking of spinning up my own . My choice is heroku ( open to changing ) , and the choice of the gerber parser/viewer is gerbv ( again , open to changing ) I have read about buildpacks and vagrant and perhap... | gcc -Wall -fPIC -c *.c | Installing gerbv on Heroku |
Python | I have a numpy operation that looks like the following : where x , y and c have the same shape . Is it possible to use numpy 's advanced indexing to speed this operation up ? I tried using : However , I did n't get the result I expected . | for i in range ( i_max ) : for j in range ( j_max ) : r [ i , j , x [ i , j ] , y [ i , j ] ] = c [ i , j ] i = numpy.arange ( i_max ) j = numpy.arange ( j_max ) r [ i , j , x , y ] = c | Optimize a numpy ndarray indexing operation |
Python | I have data about soccer teams from three different sources . However , the 'team name ' for the same team from each of these sources differ in style . For e.g.Now very often I have to compare these team names ( from different or the same sources ) to check they 're the same or different team . For e.g.I wanted to know... | [ Source1 ] [ Source2 ] [ Source3 ] Arsenal ARS ArsenalManchester United MNU ManUtdWest Bromwich Albion WBA WestBrom Arsenal == ARS : TrueMNU == WBA : FalseWBA == WestBrom : True class Team : def __init__ ( self , teamname ) : self.teams = [ ( Arsenal , ARS , Arsenal ) , ( Manchester United , MNU , ManUtd ) , ( West Br... | Finding equality between different strings that should be equal |
Python | To copy a nested list in an existing list , it is unfortunately not sufficient to simply multiply it , otherwise references are created and not independent lists in the list , see this example : To achieve your goal , you could use the range function in a list comprehension , for example , see this : This is a good way... | x = [ [ 1 , 2 , 3 ] ] * 2x [ 0 ] is x [ 1 ] # will evaluate to True x = [ [ 1 , 2 , 3 ] for _ in range ( 2 ) ] x [ 0 ] is x [ 1 ] # will evaluate to False ( wanted behaviour ) x = [ [ 1 , 2 , 3 ] for _ in [ 0 ] * n ] python -m timeit ' [ [ 1 , 2 , 3 ] for _ in range ( 1 ) ] '1000000 loops , best of 3 : 0.243 usec per l... | Why is range ( ) -function slower than multiplying items to get copies inside nested list ? |
Python | I am trying to input the following list values into the url string below.When I do the following : Python returnsWhat I would like it to do instead is to iterate through the list and return the following : Thank you . | tickers = [ 'AAPL ' , 'YHOO ' , 'TSLA ' , 'NVDA ' ] url = 'http : //www.zacks.com/stock/quote/ { } '.format ( tickers ) ` http : //www.zacks.com/stock/quote/ [ 'AAPL ' , 'YHOO ' , 'TSLA ' , 'NVDA ' ] ` http : //www.zacks.com/stock/quote/AAPLhttp : //www.zacks.com/stock/quote/YHOOhttp : //www.zacks.com/stock/quote/TSLAh... | How do I input values from a list into a string ? |
Python | This is somehow a follow-up to this questionSo first , you 'll notice that you can not perform a sum on a list of strings to concatenate them , python tells you to use str.join instead , and that 's good advice because no matter how you use + on strings , the performance is bad.The `` can not use sum '' restriction doe... | import timeimport itertoolsa = [ list ( range ( 1,1000 ) ) for _ in range ( 1000 ) ] start=time.time ( ) sum ( a , [ ] ) print ( time.time ( ) -start ) start=time.time ( ) list ( itertools.chain.from_iterable ( a ) ) print ( time.time ( ) -start ) start=time.time ( ) z= [ ] for s in a : z += sprint ( time.time ( ) -sta... | could sum be faster on lists |
Python | I appreciate the things you 're doing here . Usually I am able to figure out my issues with the help of Stackoverflow , but this time I 'm stuck . Hopefully you can help me ! The question is fairly simple : how to login on this webpage using Python 's requests ? My steps : Get the login urlProvide the login details . A... | < script > dataLayer = [ { 'environment ' : 'production ' , 'loggedIn ' : ' 0 ' , 'userCode ' : `` , 'rank ' : `` , 'totalBalance ' : ' 0 ' , 'overAgeCasino ' : ' 0 ' } ] ; < /script > < RequestsCookieJar [ < Cookie PHPSESSID=5dib6cf6kpvf29dsn725ljcec7 for .napoleongames.be/ > , < Cookie locale=en_GB for .napoleongames... | Python requests fails to log in |
Python | I would like to create a checkerboard distribution in Python.Currently I use the following script to create a 2 x 2 sized checkerboard : which createsI would like to know if there exists a simple way to generalize the above code to create a checkerboard distribution of size n x n ? EDITUsing @ jpf 's great solutionI ca... | import numpy as npimport matplotlib.pyplot as pltn_points = 1000n_classes = 2x = np.random.uniform ( -1,1 , size= ( n_points , n_classes ) ) mask = np.logical_or ( np.logical_and ( x [ : ,0 ] > 0.0 , x [ : ,1 ] > 0.0 ) , \np.logical_and ( x [ : ,0 ] < 0.0 , x [ : ,1 ] < 0.0 ) ) y = np.eye ( n_classes ) [ 1*mask ] plt.s... | Create checkerboard distribution with Python |
Python | For example , if I callI get a sorted list . Now , in the future , if I want to perform some other kind of sort on L , does Python automatically know `` this list has been sorted before and not modified since , so we can perform some internal optimizations on how we perform this other kind of sort '' such as a reverse-... | L = [ 3,4,2,1,5 ] L = sorted ( L ) | Does Python keep track of when something has been sorted , internally ? |
Python | For some reason , Cython is returning 0 on a math expression that should evaluate to 0.5 : Oddly enough , mix variables in and it 'll work as expected : Vanilla CPython returns 0.5 for both cases . I 'm compiling for 37m-x86_64-linux-gnu , and language_level is set to 3.What is this witchcraft ? | print ( 2 ** ( -1 ) ) # prints 0 i = 1print ( 2 ** ( -i ) ) # prints 0.5 | Cython returns 0 for expression that should evaluate to 0.5 ? |
Python | When assigning a variable to an anonymous function using a one line if statement , the 'else ' case does not behave as expected . Instead of assigning the anonymous function listed after the 'else ' , a different anonymous function is assigned . This function returns the expected anonymous function . What seems to be h... | > > fn = lambda x : x if True else lambda x : x*x > > fn ( 2 ) 2 > > fn = lambda x : x if False else lambda x : x*x > > fn ( 2 ) < function < lambda > at 0x10086dc08 > > > fn ( 'foo ' ) ( 2 ) 4 > > fn = ( lambda x : x*x , lambda x : x ) [ True ] > > fn ( 2 ) 2 > > fn = ( lambda x : x*x , lambda x : x ) [ False ] > > fn... | anonymous function assignment using a one line if statement |
Python | How can we detect if a Python variable is an import from __future__ ? I 've noticed it 's a class , specifically , __future__._Feature ( ) . However , all attempts at importing that class seem to fail.type ( ) returns < class '__future__._Feature ' > My attempts at getting the _Feature class : | > > > from __future__ import absolute_import > > > absolute_import_Feature ( ( 2 , 5 , 0 , 'alpha ' , 1 ) , ( 3 , 0 , 0 , 'alpha ' , 0 ) , 16384 ) > > > type ( abolute_import ) < class '__future__._Feature ' > > > > from __future__ import _FeatureSyntaxError : future feature _Feature is not defined > > > import __futur... | How to detect whether Python variable is an import from future |
Python | I have a dataframe df and a column df [ 'table ' ] such that each item in df [ 'table ' ] is another dataframe with the same headers/number of columns . I was wondering if there 's a way to do a groupby like this : Original dataframe : After groupby : I found this code snippet to do a groupby and lambda for strings in ... | name tableBob Pandas df1Joe Pandas df2Bob Pandas df3Bob Pandas df4Emily Pandas df5 name tableBob Pandas df containing the appended df1 , df3 , and df4Joe Pandas df2Emily Pandas df5 df [ 'table ' ] = df.groupby ( [ 'name ' ] ) [ 'table ' ] .transform ( lambda x : ' '.join ( x ) ) | How to aggregate , combining dataframes , with pandas groupby |
Python | The code below executes as expected by returning the total finish time as almost zero because it does n't wait for the threads to finish every job.But with the with command it does wait : Why ? What is the reason that with has this behavior with multithreading ? | import concurrent.futuresimport timestart = time.perf_counter ( ) def do_something ( seconds ) : print ( f'Sleeping { seconds } second ( s ) ... ' ) time.sleep ( seconds ) return f'Done Sleeping ... { seconds } 'executor= concurrent.futures.ThreadPoolExecutor ( ) secs = [ 10 , 4 , 3 , 2 , 1 ] fs = [ executor.submit ( d... | function of ` with ` in ` concurrent.futures ` |
Python | i have a sequence of numbers like : I want to convert them into a form where they start from the lowest number possibleExample : I tried to do : But it converts numbers like 5675 to 1234 , so it does n't work.Is there a better way to do this and what am i doing wrong ? | 12345678778899 5678 would be 1234778899 would be 1122332452 would be 1231 index = 0digit = 1newCode = [ ] newCode.append ( digit ) while index ! = len ( codice ) -1 : index += 1 if code [ index ] == code [ index-1 ] : newCode.append ( digit ) else : digit += 1 newCode.append ( digit ) | Convert a number into another according to a rule |
Python | I 've got a DataFrame that indicates members of a project and the project start date , and a second DataFrame that indicates birth dates . I 'm trying to add a number of columns indicating the total number of people in certain age groups based on the start of each project . I 've considered using .apply ( ) or .iterrow... | print ( projects ) Start John Bob GladysProject A 2014-01-08 1 0 0B 2016-08-09 0 1 1C 2018-02-06 0 1 0print ( birthdays ) birthname John 1983-04-06Gladys 1969-08-02Bob 1946-11-03 Start John Bob Gladys 25-34 35-45 46-55 56+Project A 2014-01-08 1 0 0 1 0 0 0B 2016-08-09 0 1 1 0 0 1 1C 2018-02-06 0 1 0 0 0 0 1 | Add summary columns to a pandas dataframe based on matching values in a different dataframe |
Python | I have df with column salary_dayI 'm trying to get alternative dates present for each day.For May 2020 : thursdays in may : 7,14,21,28 , fridays in may : 1,8,15,22,29 Expected output for alternative Thursday and Friday for the month of May : dfFor June 2020 : Thursdays in june : 4,11,18,25Friday in june : 5,12,19,26 As... | salary_day 0 thursday 1 friday salary_day req_datesthursday 7,21 friday 1,15,29 salary_day req_datesthursday 4,18friday 12,26 salary_day req_dates0 Monday 4,181 Tuesday 5,192 Wednesday 6,203 Thursday 7,214 Friday 1,15,29 5 Saturday 2,16,30 6 Sunday 3,17,31 | Python Dataframe : Get alternative days based on month ? |
Python | After a good while of research , I 've been unable to find why this code counts the capital letters in a sentence when they 're all capitalized , but will count `` 0 '' capital letters if I were to enter a sentence that contains any lowercase letters , such as : `` Hello World '' . | message = input ( `` Enter your sentence : `` ) print ( `` Capital Letters : `` , sum ( 1 for c in message if message.isupper ( ) ) ) | Why does this code only work when the input is all capital letters ? |
Python | I 'd like to map a value through a dictionary multiple times , and record the intermediate values . Since list.append ( ) does n't return a value , below is the best I 've been able to come up with . Is there a better way to do this in Python , perhaps using a list comprehension or recursion ? Output : | def append ( v , seq ) : seq.append ( v ) return vdef multimap ( value , f , count ) : result = [ ] for _ in range ( count ) : value = append ( f [ value ] , result ) return resultprint ( multimap ( ' a ' , { ' a ' : ' b ' , ' b ' : ' c ' , ' c ' : 'd ' , 'd ' : ' a ' } , 4 ) ) [ ' b ' , ' c ' , 'd ' , ' a ' ] | Multi-mapping a value while saving intermediate values |
Python | I do not know if the problem I am talking about has a name , if that is the case , I would like to know it in order to do more research.To explain my problem , it is easier to visualize it.I will give a representation but many others have been possible . In a small town , the police found a large number of corpses . Fo... | C1 - > [ S1 , S3 ] C2 - > [ S1 , S3 , S4 ] C3 - > [ S2 ] C4 - > [ S2 , S3 ] C1 - > S1C2 - > S4C3 - > S2C4 - > S3 found = [ ] for corpse in corpses : corpse.suspects = [ s for s in corpse.suspsects if s not in found ] if len ( corpse.suspects ) == 1 : found.append ( suspects [ 0 ] ) continue # Restart the loop to remove... | Which algorithm can rationally reduce multiple lists ? ( `` who killed who '' problem ) |
Python | I have pandas DataFrame which looks like this : And I need to make a string out of it which looks like this : I 'm a beginner and I really do n't get how do I do it ? I 'll probably need to apply this to some similar DataFrames later . | Name Number Description car 5 red `` '' '' Name : carNumber : 5 Description : red '' '' '' | Making a string out of pandas DataFrame |
Python | I use social-auth-app-django for my django website.Login all works , but after the token expires . I cant access the google 's user data anymore.I found how to refresh the token , but it givesHere is some of my codein my settings file : | File `` /mnt/s/github/nascentapp/app/booking/management/commands/sendmail.py '' , line 17 , in handle new_token = self.get_token ( user=booking_user , provider='google-oauth2 ' ) File `` /mnt/s/github/nascentapp/app/booking/management/commands/sendmail.py '' , line 28 , in get_token social.refresh_token ( strategy ) Fi... | social-auth-app-django : Refresh access_token |
Python | If my code uses third party modules that can not be trusted , is there anything to prevent situation like this : UntrustedModule.py : MyModule.py : where just importing this module breaks assumptions about other , unrelated ones ? | import randomrandom.random = lambda : 4 import randomimport UntrustedModuleprint ( random.random ( ) ) | Protecting imported modules from being corrupted by third party code |
Python | If I have an object , and within that object I 've defined a variable , which of these methods would be considered 'best ' for accessing the variable ? Method OneUsing a getter functionMethod TwoUsing the @ property decoratorMethod ThreeSimply accessing it directlyAre any of these methods more pythonic than the others ... | class MyClass : def __init__ ( self ) : self.the_variable = 21 * 2 def get_the_variable ( self ) : return self.the_variableif __name__ == `` __main__ '' a = MyClass ( ) print ( a.get_the_variable ( ) ) class MyClass : def __init__ ( self ) : self._the_variable = 21 * 2 @ property def the_variable ( self ) : return self... | Which of these is the best practice for accessing a variable in a class ? |
Python | I have a function that expects to operate on a numeric type . I am reading the numbers to operate on from a file , so when I read them they are strings , not numeric . Is it better to make my function tolerant of other types ( option ( A ) below ) , or convert to a numeric before calling the function ( option ( B ) bel... | # Option ( A ) def numeric_operation ( arg ) : i = int ( arg ) # do something numeric with i # Option ( B ) def numeric_operation ( arg ) : # expect caller to call numeric_operation ( int ( arg ) ) # do something numeric with arg | Python convert style : inside or out of function ? |
Python | I am working on a data manipulation exercise , where the original dataset looks like ; Here the columns a , b , c are categories whereas x , x2 are features . The goal is to convert this dataset into following format ; Can I get some help on how to do it ? On my part , I was able to get in following form ; This gave me... | df = pd.DataFrame ( { 'x1 ' : [ 1 , 2 , 3 , 4 , 5 ] , 'x2 ' : [ 2 , -7 , 4 , 3 , 2 ] , ' a ' : [ 0 , 1 , 0 , 1 , 1 ] , ' b ' : [ 0 , 1 , 1 , 0 , 0 ] , ' c ' : [ 0 , 1 , 1 , 1 , 1 ] , 'd ' : [ 0 , 0 , 1 , 0 , 1 ] } ) dfnew1 = pd.DataFrame ( { 'x1 ' : [ 1 , 2,2,2 , 3,3,3 , 4,4 , 5,5,5 ] , 'x2 ' : [ 2 , -7 , -7 , -7 , 4,4... | Transforming multilabels to single label problem |
Python | Is there a Pythonic way to create a function that accepts both separate arguments and a tuple ? i.e to achieve something like this : | def f ( *args ) : `` '' '' prints 2 values f ( 1,2 ) 1 2 f ( ( 1,2 ) ) 1 2 '' '' '' if len ( args ) == 1 : if len ( args [ 0 ] ) ! = 2 : raise Exception ( `` wrong number of arguments '' ) else : print args [ 0 ] [ 0 ] , args [ 0 ] [ 1 ] elif len ( args ) == 2 : print args [ 0 ] , args [ 1 ] else : raise Exception ( ``... | Function that accepts both expanded arguments and tuple |
Python | I have an array of n length and I want to resize it to a certain length conserving the proportions.I would like a function like this : For example , the input would be an array of length 9 : If I rezise it to length 5 , the output would be : or vice versa.I need this to create a linear regression model on pyspark , sin... | def rezise_my_array ( array , new_lentgh ) l = [ 1,2,3,4,5,6,7,8,9 ] [ 1,3,5,7,9 ] | How to resize array to a certain length proportionally ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.