text stringlengths 46 37.3k | 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 en... | 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 , AA... | 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 ? <code> Name Info1 Info20 Name1 Name1-Info1 Name1-Info21 Name1 Name1-Info1 Name1-Info22 Name1 Name1-Info1 Name1-Info23 Name2 Name2-Info1 Name2-Info24 Name2 ... | 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... | __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 ... | 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 # # { foo... | 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 ... | 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 ' ... | 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 ? ... | 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 bee... | 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 ? <code> import matplotlib.pyplot as pltxvals = np.arange ( 0 , 1 , 0.01 ) yvals = xvalsplt.plot ( xvals , yv... | 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 Call... | 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 w... | 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 <code> class point : def __init__ ( se... | 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 ... | 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 wi... | 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 eval... | 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... | 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 ... | 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 . <code> from random import * seed ( ) a = randint ( 0,10 ) b = randint ( 0,10 ) c ... | 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 ... | 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 si... | 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 preven... | 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 obje... | 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 e... | 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 ther... | 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 relate... | 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 . <code> > > > import ... | 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 ... | 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 . <code> > > > print ( len.__doc__ ) len ( module , object ) Return the number of items of a sequence or mapping. > > > len ( os , 1 ) Traceback ( most re... | 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 ? <code> b=5.0*10... | 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 ? <code> 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 ? <code> if not ( ( xi > = xmin and xi < = xmax ) and ( yi > = ymin and yi <... | 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 num... | 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 ... | 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 l... | 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 . <code> [ 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 ' ... | 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 simp... | 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 resu... | 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 matc... | 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... | 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 privatestorag... | 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 . <code> 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... | 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 ? <code> a = [ ' a ' , ' a ' , ' a ' , ' b ' , 'd ' , 'd ' , '... | 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... | 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 ... | 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 ? <code> 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 : <code> 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... | 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 run... | 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/val... | 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 ? <code> In [ 1 ] : s = 'abcd'In [ 2 ] : c = ' b'In [ 3 ] : c in s ... | 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__ ... | 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 e... | 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 ... | Pythonic cumulative map |
Python : I am quite confused with the behaviour as shown below : Can someone please explain ? <code> > > > ( -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 `` lo... | 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 ? <code> 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 ImageDataG... | 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 b... | 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 vect... | 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 ... | 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 quest... | 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 shifti... | 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 : <code> import numpy as npA = np.array ( [ [ 2,3,4 ] , [ 5,6,7 ] ] ) B = [ 2,3,4 ] B in A # which returns True B = [ ... | 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... | 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 <code> -- -script/execute.py | L -- -helper -- -foo.py L -- -- -bar.py L -- - __in... | 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 ... | 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... | __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 ... | 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... | 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 ... | 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 a... | 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 . <code> for i in range ( i_max ) : for j in range ( j_max ) : r [ i , j ,... | 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 wante... | 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... | 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 . <code> tickers = [ 'AAPL ' , 'YHOO ' , 'TSLA ' , 'NVDA ' ] url = 'http : //www.zacks.com/stoc... | 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 '' restri... | 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 de... | 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 sol... | 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... | 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 ? <code> print (... | 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 seem... | 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 : <code> > > > fro... | 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 st... | 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 ? <code> import concurrent.futuresimport timestart... | 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 ? <code> 12345678778899 5678 would be 12347... | 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... | 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... | 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 '' . <code> message = input ( `` ... | 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 : <code> ... | 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 cor... | 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 . <code> Name Number Description car 5 red `` '' '' Name : carNumber : 5 Desc... | 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 : <code> File `` /mnt/s/github/nascentapp/app/booking/management/commands/se... | 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 ? <code> import randomrandom.random = lambda : 4 import randomimport UntrustedModu... | 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 th... | 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 ... | 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 ; Thi... | 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 : <code> 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 ... | 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 pysp... | 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.