text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
Python : I 'm attempting to write a program that ( For a given natural n , not greater than 50 ) : Writes all possible combinations of 2n parentheses that are correct , which means that at every line of the otput there 's a sequence of parentheses with those properties : The sequence has n open , n closed parenthesesAt... | A program supposed to write all correct parantheses in Python |
Python : Is there a function that can print a python class ' heirarchy in tree form , like git log -- graph does for git commits ? Example of what I 'd like to do : Example of what the output might look like ( but variations are fine ) . Bonus points if the mro can also be read off directly from the graph , as I 've do... | Is there a simple way to print a class ' hierarchy in tree form ? |
Python : I am having a hard time trying to understand why my Gaussian fit to a set of data ( ydata ) does not work well if I shift the interval of x-values corresponding to that data ( xdata1 to xdata2 ) . The Gaussian is written as : where A is just an amplitude factor . Changing some of the values of the data , it is... | Gaussian data fit varying depending on position of x data |
Python : I was trying to write a function to remove duplicates from a list in Python.But after I did this , I found the list was sorted by converting it into set and back to a list.Here is the script : The set s is ordered ( at least ordered when printing it ) .Why the set is ordered ? And what is the time complexity i... | Why the set is ordered when converting a list to set ? |
Python : I am trying to fetch reddit account name from reddit feed window , from the following link : Now , here I am able to fetch twitter account details successfully using following code : However , I am not able to get reddit account using similar method ? ? Even I have tried fetching directly using simple xpath bu... | Unable to fetch ` href ` from Reddit embedded feed window using scrapy |
Python : I 'm wondering if it 's possible to overload the multiple comparison syntax in python : I know it 's possible to overload single comparisons , is it possible to overload these ? <code> a < b < c | Is it possible to overload the multiple comparison syntax in python ? |
Python : I have a pandas dataframe like this : I now want to sort year column first and then month column , like this below : How do i do this ? <code> column_year column_Month a_integer_column0 2014 April 25.3265311 2014 August 25.5445542 2015 December 25.6782613 2014 February 24.8011874 2014 July 24.990338 ... ... ..... | How to sort pandas dataframe by two date columns |
Python : Can anyone explain to me why the two functions below a and b are behaving differently . Function a changes names locally and b changes the actual object.Where can I find the correct documentation for this behavior ? Output : <code> def a ( names ) : names = [ 'Fred ' , 'George ' , 'Bill ' ] def b ( names ) : n... | Python confusing function reference |
Python : I have the following dataframe : I want to read EACH ROW and for each value in columns a to h ( in that row ) , subtract value in column i and divide by value in column j and to replace that original value with this resultant value And to update the whole dataframe ( from columns a to h ) . How should I procee... | Update elements of dataframe by applying function involving same row elements |
Python : How can I add the tuples from two lists of tuples to get a new list of the results ? For example : We want to get I searched google and found many results how to simply add two lists together using zip , but could not find anything about two lists of tuples . <code> a = [ ( 1,1 ) , ( 2,2 ) , ( 3,3 ) ] b = [ ( ... | How to + the values in two lists of tuples |
Python : I 'm new to pandas have tried going through the docs and experiment with various examples , but this problem I 'm tacking has really stumped me.I have the following two dataframes ( DataA/DataB ) which I would like to merge on a per global_index/item/values basis.The list of items ( item_ids ) is finite and ea... | Merging two DataFrames based on indexes from two other DataFrames |
Python : I have two lists and am trying to create a matrix of all possible multiplication outcomes in a dataframe using pandas.Lists : I have multiplied every item from L1 with every item from L2 as followed to formulate all possible outcomes : Expected Output/Goal : My goal is to now represent these values as a matrix... | Matrix of all possible multipliable outcomes from two lists into dataframe |
Python : Over the course of development it sometimes becomes necessary to temporarily comment out blocks of code for testing purposes.Sometimes these comments require re-indentation of code fragments that could become difficult to take back later without introducing errors.I was wondering whether there was a `` blank i... | Is there a blank indentation in Python ? |
Python : I have the following python program , which starts three processes that each write 10000 random rows to the same file using an inherited file handle : As a result of running this , I expect the file to contain 30000 rows . If I run write_random_rows ( 10000 ) inside my main loop ( the commented out line in the... | Why does writing to an inherited file handle from a python sub-process result in not all rows being written ? |
Python : On the console I typed inI thought at first that the reason that d only kept one pair was because hash ( a ) and hash ( b ) returned the same values , so I tried : Now I 'm confused.How come in the first code listing , d only kept one pair , but in the second listing d both keys were kept despite having same h... | python dictionary conundrum |
Python : I 'm trying to solve a problem in Python/Pandas which I think is closely related to the longest path algorithm . The DataFrame I 'm working with has the following structure : For each customer , I want to find the longest sequence which does not contain A . For instance , for customer 001 , the sequence can be... | Longest path finding with condition |
Python : I only recently started using cppyy and ctypes , so this may be a bit of a silly question . I have the following C++ function : and from Python I want to pass args as a list of strings , i.e . : I have previously found this , so I usedand from Python : c_types.c_char_p expects a bytes array . However , when ca... | CPPYY/CTYPES passing array of strings as char* args [ ] |
Python : I am trying to map owners to an IP address through the use of two tables , df1 & df2 . df1 contains the IP list to be mapped and df2 contains an IP , an alias , and the owner . After running a join on the IP column , it gives me a half joined dataframe . Most of the remaining data can be joined by replacing th... | Fill dataframe nan values from a join |
Python : Trying to get my head arround why I can not match the output of the IP against a set IP and therefore render a outcome.The result is always `` BAAD '' <code> import urllibimport reip = '212.125.222.196'url = `` http : //checkip.dyndns.org '' print urlrequest = urllib.urlopen ( url ) .read ( ) theIP = re.findal... | Python newbie , equal to a string ? |
Python : I am relatively new to working with python and pandas and I 'm trying to get the value of a cell in an excel sheet with python . To make matters worse , the excel sheet I 'm working with does n't have proper column names.Here 's what the dataframe looks like : What I want to do is to print the value of the `` ... | Python pandas print value where column = X and row = Y |
Python : I have the following python code : It generates this:112358etcI wrote the same in c : It generates this:112481632etcWhy does the c program generate powers of 2 when it is using the exact same operations ? <code> a , b = 1 , 1for i in range ( 0 , 100 ) : print a a , b = b , a + b # include < stdio.h > long long... | Fibonacci sequence works in python , but not in c ? |
Python : I 'm trying to ascertain how I can create a column that `` counts down '' until the next occurrence of a value in another column with pandas that in essence performs the following functionality : In which the event column defines whether or not an event in a column occurs ( True ) or not ( False ) . And the co... | Reverse cumsum for countdown functionality in pandas ? |
Python : The problem deals with basic matrix operation . In the following code , c1 essentially equals c2 . However , the first way of computing is much faster than the second one . In fact , at first I thought the first way needs to allocate a b matrix that is twice larger than the a matrix , hence may be slower . It ... | Why one code ( matmul ) is faster than the other ( Python ) |
Python : Dataframe X : Here Col A has 1 unique value , Col B has 6 unique values , Col C has 7 unique values , Col D has 4 unique values.I need a list of all columns where unique values > 4 say.I expect to get only col B and Col C here , but I get all columns . How to achieve desired output . <code> A B C DV1 V2 V3 V4V... | Get column names with distinct value greater than specified values python |
Python : I 'm delving inside the code for WiringPi-Python for Python and I found several blocks like this : This is a bit puzzling for me because I think that this : would yield exactly the same result as this : I know that the first is declaring a new function , and the second is a reference to the original function ,... | What is the difference in these two Python statements ? |
Python : I understand that in pytest , the preferred way for setup and cleanup is to utilize yield , likeProblem is , if there is a failure in the setup part , before yield happens , the cleanup code would not get a chance to run.Is it possible that , when some critical failure occurs in setup , all testcases are skipp... | pytest : how to skip the testcases and jump right up to cleanup if something goes wrong in setup ? |
Python : I have following four tensorsH ( h , r ) A ( a , r ) D ( d , r ) T ( a , t , r ) For each i in a , there is a corresponding T [ i ] of the shape ( t , r ) .I need to do a np.einsum to produce the following result ( pred ) : However , I want to do this computation without using a for loop . The reason is that I... | Vectorising numpy.einsum |
Python : I have a large numpy array ( dtype=int ) and a set of numbers which I 'd like to find in that array , e.g. , The result array does n't have to be sorted.Speed is an issue , and since both values and searchvals can be large , does n't cut it.Any hints ? <code> import numpy as npvalues = np.array ( [ 1 , 2 , 3 ,... | Numpy int array : Find indices of multiple target ints |
Python : I have a file and its consist of multiple lists like belowI am trying to read line by line and append to a single list in python.how to do it ? I tried so far > thanks in advance <code> [ 234,343,234 ] [ 23,45,34,5 ] [ 354,45 ] [ ] [ 334,23 ] with open ( `` pos.txt '' , '' r '' ) as filePos : pos_lists=filePos... | How to converting string to list ? |
Python : I had an exercise and tried to use parts of code I found here on another person 's question , but I found that I needed a part of code that I have no idea why I do.The full code I was using for my function is this : But I only used the else as a statement , and I did n't get the result I was hoping for.I got T... | Why do I need both condition branches for the rreverse function ? |
Python : SituationConsider the following two dataframes : As you can see in dataframe df2 the column D is of categoricals data type , but otherwise df2 is identical to df1.Now consider the following groupby-aggregation operations : with results looking as follows : Questionresult_x_df1 , result_x_df2 and result_y_df1 l... | Why does pandas grouping-aggregation discard categoricals column ? |
Python : In python but This is because it stores low integers as a single address . But once the numbers begin to be complex , each int gets its own unique address space . This makes sense to me . The current implementation keeps an array of integer objects for all integers between -5 and 256 , when you create an int i... | How is python storing strings so that the 'is ' operator works on literals ? |
Python : I have a large DataFrame with the following columns : The Year column has values ranging from 1991 to 2017 . Most ID have an age value in each Year , for example : I want to fill the missing values in the age column for each unique ID based on their existing values . For example , for ID 280165 above , we know... | Pandas DataFrame Filling missing values in a column |
Python : I want to draw a line inside a torus which I have drawn with a surface plot . The line should not be visible inside the torus - like the inner side of the torus , which can only be seen at the `` ends '' of the torus ( I cut-off one half of the torus ) . The line I have drawn is however visible everywhere ( as... | How to draw a line behind a surface plot using pyplot |
Python : I have these variables with the following dimensions : and I want to compute ( A.dot ( X_r [ : , : ,n , s ] ) *B.dot ( X_u [ : , : ,n , s ] ) ) .dot ( k ) for every possible n and s , the way I am doing it now is the following : But this is super slow and I was wondering if there was a better way of doing it b... | Fastest way to use Numpy - multi-dimensional sums and products |
Python : Why the first code does n't work while the second does ? First code : AttributeError : 'module ' object has no attribute 'webdriver'Second code : <code> import seleniumdriver = selenium.webdriver.Firefox ( ) from selenium import webdriverdriver = webdriver.Firefox ( ) | Why does an import not always import nested packages ? |
Python : in Python 2.7 , why do I have to enclose an int in brackets when I want to call a method on it ? <code> > > > 5.bit_length ( ) SyntaxError : invalid syntax > > > ( 5 ) .bit_length ( ) 3 | in Python 2.7 , why do I have to enclose an ` int ` in brackets when I want to call a method on it ? |
Python : Recently I met an example of code I 've never seen before : How does it work ( if it works at all ) ? <code> try : # a simple bunch of code if sample == 0 : return True else : raise ExampleError ( ) except not ExampleError : raise AnotherExampleError ( ) | ` try ... except not ` construction |
Python : I have code that is like : How do I access Bar or Foo from f ? f.__dict__ is of little to no help , but as repr ( f ) gives < bound method Bar.foo of < __main__.Bar object at 0x10c6eec18 > > ' it must be possible , but how ? <code> class Foo : def foo ( self ) : passclass Bar : def foo ( self ) : passf = rando... | Is there a way to gain access to the class of a method when all you have is a callable |
Python : I have a date string 18 May 14:30 which corresponds to the British summertime ( WEST or UTC+1 ) . I would like to convert it to central Euopean ( summer ) time.Here is my codeSo my problem in the third attempt I had to manually specify GMT-1 whereas CET automatically transforms to CEST . I hoped this would wor... | Deal with Birtish summer time |
Python : Goal is to write an algorithm that calculates 'initial lists ' ( a data-structure ) in a complexity class better than O ( m^2 ) What are initial list ? Let U be a set of tuples ( for example { ( 2,5 ) , ( 5,1 ) , ( 9,0 ) , ( 6,4 ) } ) .Step 1 : L1 is ordered by the first element of the tuple : and L2 by the se... | Algorithm to calculate 'initial lists ' in O ( m*log m ) |
Python : I want to sample ~10⁷ times from a population of ~10⁷ integers without replacements and with weights , each time picking 10 elements . After each sampling I change the weights . I have timed two approaches ( python3 and numpy ) in the following script . Both approaches seem painfully slow to me , do you see a ... | Speed up random weighted choice without replacement in python |
Python : I have a 2D list of 416 rows , each row having 4 columns . Rows 1-4 contain their row number 4 times ( i.e. , [ ... [ 1,1,1,1 ] , [ 2,2,2,2 ] ... ] . Row 330 contains [ 41,22,13,13 ] . Everything else is [ 0,0,0,0 ] . Currently I am using a for loop with many explicit if statements . What is a more efficient w... | How to define a large list array in Python using For loop or Vectorization ? |
Python : I have the following list : The number of list of lists in a can vary , but the no . of elements in each list of lists will remain same.for example , like below : orso for the input : I 'm expecting the below output : Based on the no . of list of lists , the lists should be duplicated as shown in the above for... | Duplicating a list based on elements in its list of lists |
Python : I got some really simple code below . # ! /usr/bin/python from multiprocessing import Pool import timeAs you can see , I have a worker to handle 1000 jobs use multiprocessing.If the job is 25-30 , then the worker will sleep 10s . This is try to simulate a time/resource cost job.When I run the above code , the ... | Why Python multiprocessing is running sequencially ? |
Python : I have the following dummy dataframe : The real dataset has shape 500000 , 90.I need to unnest these values to rows and I 'm using the new explode method for this , which works fine . The problem is the NaN , these will cause unequal lengths after the explode , so I need to fill in the same amount of delimiter... | Fill in same amount of characters where other column is NaN |
Python : I have the following lines of code : It prints : I am baffled ... Any explanation ? Python 3.6.0 , Windows 10I have a rock solid confidence in the quality of the Python interpreter ... And I know , whenever it seems the computer makes a mistake , it 's actually me being mistaken ... So what am I missing ? [ ED... | Paradoxical behaviour of math.nan when combined with the 'in ' operator |
Python : I get an UnboundLocalError when I reimport an already imported module in python 2.7 . A minimal example isHowver , when the nested import is placed as the first statement in the function definition then everything works : Can someone please explain why the first script fails ? Thanks . <code> # ! /usr/bin/pyth... | UnboundLocalError on nested module reimport |
Python : I 'm trying to replace the occurrence of a word with another : Whereas this works ... the occurrence of ugh in laughing is also being replaced in the output : ladisappointeding disappointed.How does one avoid this so that the output is laughing disappointed ? <code> word_list = { `` ugh '' : `` disappointed ''... | Python string replacement |
Python : How is this sorting code working ? I can not understand how the values returned by the iterator are being used to sort the list ? Output : <code> mylist= [ `` zero '' , '' two '' , '' one '' ] list1= [ 3,1,2 ] it = iter ( list1 ) sorted ( mylist , key=lambda x : next ( it ) ) [ 'two ' , 'one ' , 'zero ' ] | How is this sorting code working ? |
Python : I created a zip file with Gnome Archive Manager ( Ubuntu OS ) . I created the zip file with a password and I am trying to unzip it using the zipfile Python library : When I run this code I get the following error and I am pretty sure that the password is correct . The error is : How can I unzip the file ? <cod... | Unable to unzip a .zip file with a password with python zipfile library |
Python : Im trying to rotate a list of list 90 degrees . For example , change this : toVisually : Whenever I change the list size to be more elements or less it always says the index is out of range ? What is going on ? <code> [ [ 1,2,3 ] , [ 4,5,6 ] , [ 7,8,9 ] ] [ [ 7,4,1 ] , [ 8,5,2 ] , [ 9,6,3 ] ] [ [ 1,2,3 ] , [ [... | list index out of range , whenever I change the list size |
Python : I want to set my LSTM hidden state in the generator . However , the set of the state only works outside the generator : The generator is invoked in the fit_generator function : This is the result when I print the state : This is the error that occurs in the generator : What am I doing wrong ? <code> K.set_valu... | Setting Keras Variables in Generator |
Python : I noted thatyields an error.I can see , why that is forbidden . But how ? Can I use that in `` normal '' code ? <code> int.__str__ = lambda x : pass | How are built-in types protected from overwriting ( assigning to ) their methods ? |
Python : Is there an option how to filter those strings from list of strings which contains for example 3 equal characters in a row ? I created a method which can do that but I 'm curious whether is there a more pythonic way or more efficient or more simple way to do that.EDIT : I 've just found out one solution : But ... | Filter strings where there are n equal characters in a row |
Python : I think it 's a bit weird question to ask.The thing is that while I was studying some parts of django code I came across something I 've never seen before.According to Copy Difference Question andIt 's usage in dictionary we can create two dictionary with same reference.The question is what is the purpose of s... | Why setting a dict shallow copy to itself ? |
Python : I had a Python module which included a while loop which was supposed to run for a fixed amount of time . I did this by adding a constant to the output of time.time ( ) and running until time.time ( ) was greater than that variable . This did not present any issues , but the same thing is not working for me in ... | time.time ( ) not working to run while loop for predetermined time in Cython |
Python : I have a dataframe like : The dataframe is quite big , with over 80 thousand rows , and ids column may contain easily over thousands , even 10 thousands comma separated id . Ids in a given row would be unique in the comma separated string.I would like to construct a dataframe which calculated Jaccard 's index ... | Calculate intersection over union ( Jaccard 's index ) in pandas dataframe |
Python : What is the correct way to type an `` interface '' in python 3 ? In the following sample : what would be the correct way to type the return value of the factory function ? It should be something like `` A type with a single method named foo that accepts no arguments and returns an integer '' .But not sure I ca... | Typing interfaces |
Python : So I have this class called Person , that basically has the constructor name , id , age , location , destination and what I want to do is that when I want to make a new person , I want it to open from a txt file.For example , this is my Person Class ( in the Module , People ) So basically , instead of me havin... | Calling from a txt to define something ... Python |
Python : If I do this : I get p= [ 0 , 1 , ' a ' , ' b ' , 6 , 7 , 8 , 9 ] which means Python is replacing the the elements indexed 2-5 with the new list [ ' a ' , ' b ' ] .Now when , I doPython says ValueError : attempt to assign sequence of size 2 to extended slice of size 4Why does it resize the list in the first ca... | List slice assignment with resize using negative indices |
Python : Let 's imagine I have a binary 40*40 matrix.In this matrix , values can be either ones or zeros.I need to parse the whole matrix , for any value == 1 , apply the following : If the following condition is met , keep the value = 1 , else modify the value back to 0 : Condition : in a square of N*N ( centered on t... | Any idea to optimise this algorithm ? |
Python : I 'm using a 3rd-party Python module that does something horrible , like : I 've got a class that subclasses str : I 'd like to call foo ( ) on a mystr instance , but it fails because type ( mystr ) ! = type ( str ) . Is there any way I can make my class so that type ( mystr ) == type ( str ) and hence get foo... | How to change result of type ( object ) ? |
Python : I 'm looking into something that seems simple and I can only find complicated answers.I 'm doing some iterations on a function `` BT '' that yields several dataframes . I would like to get the `` iterated '' results directly as the output of my function , just differentiating them by their name . I want i to v... | Python loop with dynamically named outputs |
Python : I have trouble with some code . I want my code to compare 2 Lists contained in a List of multiple Lists but only one time each.This prints : And i would like this result : Thanks you for your help ! <code> resultList = [ [ 'Student1 ' , [ 'Sport ' , 'History ' ] ] , [ 'Student2 ' , [ 'Math ' , 'Spanish ' ] ] ,... | Compare multiple Lists only one time each in python |
Python : Is it possible to use as in if statement like with that we use , for example : This is my code : Can I use if in this type : In first if I called my_list four times . I can use a variable but I want to know is there any way to use as ? <code> with open ( `` /tmp/foo '' , `` r '' ) as ofile : # do_something_wit... | Can I use the `` as '' mechanism in an if statement |
Python : I plan on making a chart with ggplot in a python script . These are details about the project : I have a script that runs on a remote machine and I can install anything within reason on the machineThe script runs in python and has data that I want to visualize stored as a dictionaryThe script runs daily and th... | Comparing Plumbr to other options for making a chart with R in a Python script |
Python : Basically I want : with a single timeout for both actions and - that 's important - with an error message telling which action timed out.For comparison , with just one action : Now with two actions I have this and do n't like it.I find it really counter-intuitive to have : where timeout handling is the main fu... | Two async operations with one timeout |
Python : I have a large data file ( N,4 ) which I am mapping line-by-line . My files are 10 GBs , a simplistic implementation is given below . Though the following works , it takes huge amount of time.I would like to implement this logic such that the text file is read directly and I can access the elements . Thereafte... | How to read a large text file avoiding reading line-by-line : : Python |
Python : I 'm trying to make a bot where when you type for example `` ! say hello world '' and the bot would reply with `` Hello World '' . But when I try to do spaces it does n't work.So when I simply type `` ! say Hello '' it shows this : As you can see it works fine but when I put a space for example `` ! say hello ... | Bot only takes one command |
Python : I have the following square DataFrame : this is modified distance matrix , representing pairwise distance between objects [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' ] , where each row is divided by a coefficient ( weight ) and all diagonal elements artificially set to np.inf.How may I get a list/vector of indices ... | *Vectorized* way to find indices of minimums for each column ( excluding all already found indices ) |
Python : I have the following DataFrame structure : What I need to display is : In the profile_id column I have a couple of ids separated with a comma , and I need to loop through each id . <code> profile_id user birthday123 , 124 test1 day1131 , 132 test2 day2 profile_id user birthday123 test1 day1 124 test1 day1131 t... | Manipulate pandas dataframe to display desired output |
Python : Does Python interpreter gracefully handles cases where an object instance deletes the last reference to itself ? Consider the following ( admittedly useless ) module : and now the usage : This would still print I 'm still here , but is there a race condition with Python 's garbage collector which is about to c... | Object deletes reference to self |
Python : I have a numpy array A with n rows of size 3 . Each row is composed by three integers , each one is a integer which refers to another position inside the numpy array . For example If I want the rows refered by N [ 4 ] , I use N [ N [ 4 ] ] . Visually : I am building a function that modifies N , and I need to m... | Strange assignment in numpy arrays |
Python : I have a data frame like this : I want to select col2 values for every 1 , 5 and 10 values of col1 . If col1 value is not 1 , 5 or 10 keep the col2 values where col1 values is nearest to 1,5 or 10for example the final df will look like : how to do it using pandas without using any loop <code> dfcol1 col2 1 10 ... | find col2 values based on certain col1 value , if not presents keep nearest value using pandas |
Python : my python script is supposed to write to /dev/xconsole . It works as expected , when I am reading from /dev/xconsole , such as with tail -F /dev/xconsole . But if I do n't have tail running , my script hangs and waits.I am opening the file as follows : and writing to it : Why does my script hang , when nobody ... | python script hangs when writing to /dev/xconsole |
Python : I want to return a boolean value True or False depending on if the string contains only 1 's and 0 's . The string has to be composed of 8 1 's or 0 's and nothing else . If it only contains 1 's or 0 's , it will return True and if not it will return False.This is what I have so far but I 'm just not sure how... | How to tell if a string has exactly 8 1 's and 0 's in it in python |
Python : I want to specify a type hint for a function can receive either a list of strs or a list of ints . Is there a way to do this using Python ? Something like : <code> from typing import Listdef my_function ( list_arg : List [ str|int ] ) : ... ... | Use python 's typing library to specify more than one possible type |
Python : I am very new to Python , and I wonder what the following line of code is doing and how could it be written in R : For instance , what is the meaning of lambda x : ( 0 , 1 ) ? P.S.df is a pandas dataframe <code> df [ 'sticky ' ] = df [ [ 'humidity ' , 'workingday ' ] ] .apply ( lambda x : ( 0 , 1 ) [ x [ 'work... | How to convert this confusing line of Python into R |
Python : I want to make a tic tac toe game , and I am making it so when the user inputs a number 1 - 9 , it makes an X on the corresponding space on the grid . here 's the function for that : and so , the grid shows up with the X at the right place . But then the next turn comes . And I want to have them enter a new nu... | Combine same function with different parameters - Python |
Python : What 's going on here ? We suddenly get what appears to be a a string containing the float 1.0 ! ? ... though it turns out it 's simply a float.What 's the philosophy behind this ? I understand that numpy wants to be stricter about things like types and typing rules in order to be more efficient than basic pyt... | Curious Modulus Operator ( % ) Result |
Python : I want to divide an uncomplete graph into seperate , unconnected bodies . The edges of the graph are in the list edges . The code gives a different result upon shuffling the order of the edges . Why is that ? Expected output : [ { ' 1 ' , ' 2 ' , ' 8 ' , ' 4 ' , ' 6 ' , '10 ' } , { ' 9 ' , ' 5 ' , ' 7 ' } ] So... | Different result upon shuffling a list |
Python : I have a dictionary , which the keys are integers . I arbitrarily changed one of the keys to a date , and I need to change the other keys.Sample data : Expected output : Current code so far : <code> { ' C-STD-B & M-SUM ' : { datetime.date ( 2015 , 7 , 12 ) : 0 , -1 : 0.21484699999999998 , -2 : 0.245074 , -3 : ... | Change multiple keys from dictionary , while doing timedelta operation in Python |
Python : I want to parse a string to extract all the substrings in curly braces : should produce : Then I want to format the string to print the initial string with the values : How can I do that ? <code> 'The value of x is { x } , and the list is { y } of len { } ' ( x , y ) str.format ( 'The value of x is { x } , and... | Extract substrings in python |
Python : I have a very long array , and I 'm trying to do the following in a way as efficient as possible : For each consecutively incrementing chunk in the list I have to reverse its order.So , for the following array : I would like to obtain : I was wondering if this could be vectorized , using numpy perhaps ? I have... | Reverse order sequential digits |
Python : Given the following code : When run , Python complains : UnboundLocalError : local variable ' a ' referenced before assignmentHowever , when it 's a dictionary ... The thing runs just fine ... Anyone know why we can reference a in the 2nd chunk of code , but not the 1st ? <code> a = 0def foo ( ) : # global a a... | Python variable resolving |
Python : I have the following DF : If I do df.dtypes , I get get the following output : Howeverm col1 contains Only Date information ( DATE ) , whereas col2 contains both date and time information ( DATETIME ) .Whats the easiest way to determine wheter a column contains DATE or DATETIME information ? Data generation : ... | Easiest way to determine whether column in pandas Dataframe contains DATE or DATETIME information |
Python : I have a large dataframe containing , amongst other things , a ( Norwegian ) social security number . It is possible to get the date of birth out of this number via a special algorithm . However , every now and then an illegal social security number creeps into the database corrupting the calculation . What I ... | How to tag corrupted data in dataframe after an error has been raised |
Python : Recently , I had to convert the values of a dictionary to a list in Python 3.6 and an use case where this is supposed to happen a lot.Trying to be a good guy I wanted to use a solution which is close to the PEP . Now , PEP 3106 suggestswhich obviously works fine - but using timeit on my Windows 7 machine i see... | PEP 3106 suggests slower way ? Why ? |
Python : For example , I have text with a lot of product dimensions like `` 2x4 '' which I 'd like to convert to `` 2 xby 4 '' .One way of describing what I want to do is repeat the replacement until no more replacements can be made . For example , I can simply to the above replacement twice to get what I wantBut I ass... | How to replace all occurrences of regex as if applying replace repeatedly |
Python : I am trying to get sum of dynamic columns based on certain condition.dataframe df has all the columns listed above.If ID = 2 , I need sum of first two columns A , BIF ID = 3 , I need sum of first three columns A , B , Cabove line of code is giving an error that : Note : ID can be any number but it would be alw... | sum of dynamic columns based on certain condition |
Python : So this is a weird problem that I suspect is really simple to solve . I 'm building a lyrics webapp for remote players in my house . It currently generates a dictionary of players with the song they 're playing . Eg : Occasionally subsets of these players are synced . So —as above— they display the same value ... | Merging dictionary keys if values the same |
Python : I have found examples of how to remove a column based on all or a threshold but I have not been able to find a solution to my particular problem which is dropping the column if the last row is nan . The reason for this is im using time series data in which the collection of data doesnt all start at the same ti... | How Can I drop a column if the last row is nan |
Python : Suppose I have this numpy array : My goal is to select two random elements from each row and create a new numpy array that might look something like : I can easily do this using a for loop . However , is there a way that I can use broadcasting , say , with np.random.choice , to avoid having to loop through eac... | How do you broadcast np.random.choice across each row of a numpy array ? |
Python : I have a 2D array of shape ( M*N , N ) which in fact consists of M , N*N arrays . I would like to transpose all of these elements ( N*N matrices ) in a vectorized fashion . As an example , This code generates the following output : Which I expect . But I want the vectorized version . <code> import numpy as npA... | Transposing arrays in an array |
Python : The documentation of all ( ) reads that it returns True is all the elements are True/For an empty list.Why does all ( [ [ ] ] ) evaluate to False ? Because [ ] is a member of [ [ ] ] , it should evaluate to True as well . <code> > > all ( [ ] ) True > > all ( [ [ ] ] ) False > > all ( [ [ [ ] ] ] ) True > > al... | Behaviour of all ( ) in python |
Python : I 'd like to log user activity in my app for presentation to users and also for administrative purposes . My customers are companies so there are three levels at which I may be presenting activity : Activity of a single userActivity of all users of a companyAll activityTo do the logging , I would create a mode... | Creating your own activity logging in GAE/P |
Python : I have a data frame with the image number ( sliceno ) and x and y coordinates ( x-position and y-position , respectively ) . These images are taken over time and the same slice number indicates multiple coordinates recorded at the same timepoint.I want to compare coordinates of images to the one ( s ) before .... | How to apply function on variable based on consecutive values in another variable |
Python : I have this array : And these boolean indices : I want to find the index of the maximum value in the array where the boolean condition is true . So I do : Which works and returns 1 . But if I had an array of boolean indices : Is there a vectorized/numpy way of iterating through the array of boolean indices to ... | How do I vectorize this loop in numpy ? |
Python : I got a fairly big dataframe from a csv in pandas.The problem is that on some columns I get strings of text which I would like to isolate the last character to turn it into integers.I found a solution , but I am fairly sure it 's not the most efficient.It goes like this : In terms of writing , this is not real... | How to modify full text of some columns in pandas |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.