text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
Python : Requirement : Here when last occurence of loyal with value is 1 then set flag as 1 else 0Input : Output Required : Note : Here Flag only checks whether last loyal value containing 1 and set the flag.What i tried : Here there are two scenarios :1 . Value 1 with preceding 0 ( for your reference row_num 4 for con... | How can we set a flag for last occurence of a value in a column of Pyspark Dataframe |
Python : I have following dataframe : I am trying the following : How do I get the following instead : <code> df1 = pd.DataFrame.from_dict ( { ' A ' : [ 3,5,1,7 ] , 'DateTime ' : pd.date_range ( `` 11:00 '' , `` 14:00 '' , freq= '' 60min '' ) } ) .set_index ( 'DateTime ' ) df2 = pd.DataFrame.from_dict ( { ' B ' : [ 13,... | Concating pandas dataframe |
Python : I want to parse a LaTeX document and mark some of its terms with a special command . Specifically , I have a list of terms , say : and I want to mark the first occurrence of Astah in the text with this custom command : \gloss { Astah } . So far , this works ( using Python ) : and it works fine.But then I found... | Negative regular expression before specific term |
Python : So here I have a problem . Let 's say I have 2 parent classes . They both inherit from a master class . Then they are both parent classes to a child class . Is there a way to figure out ( let 's say I 'm Father ) which Mother class I 'm `` having a child with ? '' I do n't need the child to figure out which mo... | Python : Figure out `` Spouse '' class ? |
Python : I have an object that looks like this : each one of the keys has a number of available options as denoted by the list ( e.g . a can choose between A , B , C and so on ) . I want to find a combination of pairs that will satisfy everyone . This could be : So in the example above a chose item B , reducing the poo... | Find viable combination from a list of preferences |
Python : So I found out that the easiest way of grouping and counting elements is through itertools . I have this list of `` Employee Departments '' ( e.g . Accounting , Purchasing , Marketing , etc . ) and it 's over 500 . A sample of which is : What I intend to do is count all employees under a certain department the... | Count elements , then remove duplicates |
Python : I 've got a CSV file containing the distance between centroids in a GIS-model in the next format : It is sorted on origin ( InputID ) and then on the nearest destination ( TargetID ) .For a specific modelling tool I need this data in a CSV file , formatted as follows ( the numbers are the centroid numbers ) : ... | How to speed up the code - searching through a dataframe takes hours |
Python : I have a Dataframe that looks like this : and I need to transform it into a Dataframe that shows for each combination , of the values in Col 1 and Col 2 if that combination is contained in the original DataFrame : Is there a native way in pandas to get this transformation ? I was creating the transformed Dataf... | Pandas : Transform dataframe to show if a combination of values exists in the orignal Dataframe |
Python : I wanted to sort a list in-place and tried using the list itself during the sorting ( within a key function ) . I found out that the list itself appears to be empty in there.So I tried : and gotAny explanation for this ? <code> a = [ 1,4,5,3,2,6,0 ] b = [ ' b ' , ' e ' , ' f ' , 'd ' , ' c ' , ' g ' , ' a ' ] ... | List appears to be empty during sorting |
Python : I am looking to obtain the x'th largest item in a dictionary from the key 's corresponding value.For example , with the dictionary : I want to be able to easily extract ' b ' as the 3rd largest key.Initially , when I was only after the top three occurrences , I made a copy of the dictionary , found the max val... | Obtain x'th largest item in a dictionary |
Python : When using pythons random.shuffle function , I noticed it went significantly faster to use sorted ( l , key=lambda _ : random.random ( ) ) than random.shuffle ( l ) . As far as I understand , both ways produce completely random lists , so why does shuffle take so much longer ? Below are the times using timeit ... | Why is random.shuffle so much slower than using sorted function ? |
Python : Simplified dfs : I want to add a column to df which includes combinations of df [ 'ID ' ] to df2 [ 'ID_number ' ] and df [ 'value ' ] to the df2 column matching the value in df [ value ] ( either ' A ' or ' B ' ) .We can add a column of matching values where the lookup column name in df2 is given , ' A ' : Whi... | Adding df column finding matching values in another df for both indexed values and a dynamic source column ? |
Python : While using Pandas , I often encounter a case where there is an existing function which takes in multiple arguments and returns multiple values : Suppose I have a dataframe : What I want is to apply foo on df with column 0 and 1 as arguments , and put the results into new columns of df , without modifying foo ... | What is the most pythonic way to apply a function on and return multiple columns ? |
Python : Say we need a program which takes a list of strings and splits them , and appends the first two words , in a tuple , to a list and returns that list ; in other words , a program which gives you the first two words of each string.It can be written like so ( we assume valid input ) : But a list comprehension wou... | Eliminating redundant function calls in comprehensions from within the comprehension |
Python : I have two dataframes that I want to merge/groupby . They are below : I want to merge df_1.words onto df_2 , but group all values in df_1.words where df_1.start is in between df_2.start and df_2.stop . It should look like this : <code> df_1 words start stop0 Oh , 6.72 7.211 okay , 7.26 8.012 go 12.82 12.903 ah... | How to merge and groupby between seperate dataframes |
Python : This post shows how to find the shortest overlapping match using regex . One of the answers shows how to get the shortest match , but I am struggling with how to locate the shortest match and mark its position , or substitute it with another string . So in the given pattern , and the pattern I want to locate i... | Mark the shortest overlapping match using regular expressions |
Python : In my program , I wanted a variable global only under some circumstances . Say it looks like this : I was expecting the result to be : However it turned out to be : So , I was thinking , `` Okay maybe the Python compiler makes the variable global whenever it sees the 'global ' keyword no matter where it is loc... | How does 'global ' behave under an if statement ? |
Python : Say you have an iterable sequence of thing objects called things . Each thing has a method is_whatever ( ) that returns True if it fulfills the `` whatever '' criteria . I want to efficiently find out if any item in things is whatever . This is what I 'm doing now : Is that an efficient way to do it , i.e . Py... | Is this is an efficient and pythonic way to see if any item in an iterable is true for a certain attribute ? |
Python : I 'm trying to create tables on-the-fly from existing data ... however , the table I need has dual Primary Keys . I ca n't find how to satisfy the restrictions . I.e . I start with the following two tables ... When I try the following , it works ... However , both the following give me the error ... <code> sel... | Can not map ForeignKey due to dual Primary Keys |
Python : I am learning pytorch , that to do a basic linear regression on this data created this way here : I know that using tensorflow this code can solve : but I need to know what the pytorch equivalent would be like , what I tried to do was this : But the model does n't learn anything , I do n't know what I can do a... | what is the pytorch equivalent of a tensorflow linear regression ? |
Python : In this dictionary , I can access the number 1000000000000 by using NumberTextSet3 [ `` trillion '' ] .But how would I access the the last word in the dictionary , maybe like : NumberTextSet3 [ -1 ] and have it return `` trillion '' ? <code> NumberTextSet3 = { `` ten '' : 10 , `` hundred '' : 100 , `` thousand... | Python - How to access first type of data |
Python : I want to be able to use the df.fillna ( ) function on a Dataframe , but apply a conditional to it based on the Index & Column name of that particular cell.I am trying to create a heatmap of hockey linemate data based on the following dataset ( apologies for the large dictionary below ) - What I am trying to a... | Dataframe fillna conditional based on Index & Column Name |
Python : I had a math test today and one of the extra credit questions on the test wasWe were supposed to list out the steps of the loop which was easy ; but it got me thinking , why does this program run ? the second print i seems out of place to me . I would think that the i only exists for the for loop and then get ... | About variable scope ? |
Python : In Python , I 'm trying to access a file from the directory where the `` last '' function ( for lack of a better word ) is located.For example , let 's suppose I have the following files : foo.py has : helper.py has : And text.md is just an empty text file.When I directly run edit_file ( `` text.md '' ) from h... | Python - Relative file locations when calling submodules |
Python : I have a 2d pygame water simulation thingy that I followed a tutorial to make . I also found the answer to this question to fix issues with the tutorial : Pygame water physics not working as intendedI have since been trying to convert this program over to using pyopengl to render things . However , I have been... | Converting pygame 2d water ripple to pyOpenGL |
Python : This might be a very broad question . I wanted to create a way to represent strings that would support O ( 1 ) append , O ( 1 ) append to the left , and O ( 1 ) comparison while maintaining O ( N ) slicing and O ( 1 ) indexing . My idea is that I would store unicode characters as their unicode number , and use... | How are integer operations implemented in Python ? |
Python : Given a list of numbers , like this : I 'd like a list that has elements from i - > i + 3 for all i in lst . If there are overlapping ranges , I 'd like them merged.So , for the example above , we first get : But for the last 2 groups , the ranges overlap , so upon merging them , you have : This is my desired ... | Replace a list of numbers with flat sub-ranges |
Python : I am attempting to add two arrays . I want to get something out that is like So adding entries to each of the matrices at the corresponding column . I know I can code it in a loop of some sort , but I am trying to use a more elegant / faster solution . <code> np.zeros ( ( 6,9,20 ) ) + np.array ( [ 1,2,3,4,5,6,... | Adding a 1-D Array to a 3-D array in Numpy |
Python : I have a dataframe df1 like thisI want to make df2 such that , it contain all the words of df1only once with their count ( total occurrence ) and I want to sum c1 column and make a new column of it in df2 ( sum only if a word is in that row ) . Expected output : <code> id ` text c1 1 Hello world how are you pe... | Make a dataframe of all unique words with their count and |
Python : For instance , say list L = [ 0,1,2,3 ] and I want to add 10 elements of 4 : without needing to use a loop or anything <code> L= [ 0,1,2,3,4,4,4,4,4,4,4,4,4,4 ] | How do I add , say , n entries of x to a list in one shot ? |
Python : I have the following dataframe : I would like to add a colunm with the value that doesnt have the NaN value . So that : would it be using an lambda function ? or fillna ? Any help would be appreciated ! Thanks ! <code> A B C 0 NaN NaN cat1 dog NaN NaN 2 NaN cat NaN 3 NaN NaN dog A B C D0 NaN NaN cat cat1 dog N... | How to combine three string columns to one which have Nan values in Pandas |
Python : I am trying to learn regular expressions by scraping PDFs , and I seem to be running into an issue when I put a second pipe ( | ) operator in my match object.I 've tried reading various places on the web , but I ca n't seem to find anything . I am trying to retrieve just the text Base Attack/Grapple : +1/–3 in... | Second pipe operator not working for my regular expression in python |
Python : I 'm currently trying the wemake-python-styleguide and found WPS335 : Using lists , dicts , and sets do not make much sense . You can use tuples instead . Using comprehensions implicitly create a two level loops , that are hard to read and deal with.It gives this example : Is this purely personal preference or... | Does it make a difference if you iterate over a list or a tuple in Python ? |
Python : How can I check the file `` file_name '' is still open or not with this command ? I know we should use something likebut what 's happened and how can I check the behavior if I use the former command . <code> csv_gen = ( row for row in open ( file_name ) ) with open ( file_name ) as file_name_ref : csv_gen = ( ... | How can I check a file is closed or not in python ? |
Python : I have a multindex dataframe with 3 index levels and 2 numerical columns.I want to replace the values in first row of 3rd index level wherever a new second level index begins.For ex : every first rowThe dataframe is too big and doing it datframe by dataframe like df.xs ( ' A,1 ' ) ... df.xs ( A,2 ) gets time c... | Replace specific values in multiindex dataframe |
Python : In my code below , for some reason it keeps writing the output data to file even though my output data is identical to the newly produced data ... I 'm trying to make it so that it only saves when it 's different , in order to recreate my problem run the script at least three times and it should n't be printin... | Code keeps saving the document even though output is identical to original output ? |
Python : I need to convert a sparse logic matrix into a list of sets , where each list [ i ] contains the set of rows with nonzero values for column [ i ] . The following code works , but I 'm wondering if there 's a faster way to do this . The actual data I 'm using is approx 6000x6000 and much more sparse than this e... | Fastest way from logic matrix to list of sets |
Python : I think this is a bug , so not strictly on-topic on this site , but I 'd like the help of the pandas ' community here with it . Let 's consider this dataframe : If I use pd.get_dummies on the second column with a minus sign in front , here is what I get : While the expected result can be obtained using str.get... | Adding a minus sign before pd.get_dummies return 255 instead of -1 |
Python : I want to take the shape of Input data which is passed to Input layer with ( None , ) shape , and use it in a for loop for some purpose.Here 's part of my code implementation : because the Input shape is ( None , ) , I do n't know what to give to for loop as range ( at the code i describe it with 'tm_stp ' ) .... | How to get shape of previous layer and pass it to next layer ? |
Python : I 'm working with a dataset similar to this : What I 'm looking to do is find the `` least cool '' and `` coolest '' animal weighted by popularity , such that : The solution that comes to me first is to create 3 arrays ( keys , cool_factors , and popularities ) , loop through the dictionary , push all the valu... | Pythonic way to find key of weighted minimum and maximum from a dictionary |
Python : I am doing dynamic class generation that could be statically determined at `` compile '' time . The simple case that I have right now looks more or less like this : On import , the Python interpreter seems to compile to bytecode , then execute the file ( thus generating Child1 , Child2 , and Child3 ) once per ... | Permanently caching results of Python class generation |
Python : The following is the slicings syntax that I copied from The Python Language Reference : Per my understanding , this syntax equates to SomeMappingObj [ slice_item , slice_item etc ... ] which again equates to something like a [ 0:2:1,4:7:1 ] and a = [ i for i in range ( 20 ) ] . But , I ca n't test this in IPyt... | Understanding python slicings syntax as described in the python language reference |
Python : I have a DataFrame as below.Also , I have a sorting list.I am trying to add the missing columns based on the sort list and sort the DataFrame.expected output : I can get the result using the below code . Is there another ( simple ) way to do this ? my code : <code> df = pd.DataFrame ( { `` code '' : [ `` AA ''... | DataFrame columns sort by a given list and add empty columns for missing columns |
Python : So , first I like to state that I 'm very new to Python , so this probably will be an easy question . I 'm exercising my programming skills and am trying to write a simple program . It goes like this : Which , for a certain alpha and k , should give me an array sqrt [ ] . For example , if alpha = [ 1,4,9 ] and... | Array in a program |
Python : I have a multi index series as below.Then a second series with only one and three as indices : So , as far as I can see , s2 and s.loc [ pd.IndexSlice [ : , ' X ' , : ] ] are indexed identically.As such I would expect to be able to do : and yet doing so results in NaN values : What is the correct way to do thi... | pd.Series assignment with pd.IndexSlice results in NaN values despite matching indices |
Python : I am writing a simple templating engine in python , and it involves mixing python with other languages , and I need to determine the indentation level of any given line of python code.I was wondering if it 's accurate to say that a new indentation level is always indicated by a colon ( : ) at the end of the li... | How to tell if the next line should be indented when parsing python |
Python : Consider the below code : What gets printed is a dictionary : But if there were more than two rows that have the polylines in them : A Series object would have been printed : Why is that so and how can I always get Series , even if there is only one True row ? I need consistent output as I do n't know beforeha... | Why does a single row get retrieved from a dataframe as a dictionary , and not as a Series ? |
Python : I would like to call a function in a thread . Calling it with the conventional API looks like : I was wondering if there is a pythonic was of making this threaded call with a cleaner API , without defining a function which is specific for np.savez_compressed . E.g . something in the style of ( pseudo-code ) : ... | A clean API for making a function call threaded in python |
Python : I 'm creating a module with several classes in it . My problem is that some of these classes need to import very specific modules that needs to be manually compiled or need specific hardware to work.There is no interest in importing every specific module up front , and as some modules need specific hardware to... | Import on class instanciation |
Python : Novice programmer here . Self-Learning Python . First question on Stackoverflow.I am trying to write a program to recommend a restaurant based on user 's selection of price , rating and cuisine type . To achieve this , the program builds three data structures : [ I am still at an intermediate stage ] The data ... | Creating more than one data structure ( dicts ) in Python |
Python : Today I learned that Python caches the expression { } , and replaces it with a new empty dict when it 's assigned to a variable : I have n't looked at the source code , but I have an idea as to how this might be implemented . ( Maybe when the reference count to the global { } is incremented , the global { } ge... | Strange behaviour related to apparent caching of `` { } '' |
Python : I have the following example data , and I 'd like to filter a piece of data , when ( col1 = ' A ' and col2 = ' 0 ' ) we want to keep rows until next ( col1 = ' A ' ) .I want to do using pandas dataframe but I do n't know how it is.For example , we have this dataThe result I want to achieve is : Thank you very ... | a solution for filtering some rows of data based on condition in pandas |
Python : Given a list of animals , like : and pandas dataframe , df : I want to get a new dataframe showing occurrence of each animal , something like : I know I can run a loop and prepare it , but I have the list of over 80,000 words with dataframe of over 1 million rows , so it would take long to do it using loop . I... | get list of occurrences using pandas |
Python : I 'm working on a todo list in Python and I am currently stuck on printing the todo list.I have my add code and view code as such : and these are the functions im using : I 'm able to add items to a dictionary print the dictionary the first time i select the option to print list . The second time i print it gi... | Need help printing list |
Python : I want to find all data enclosed in [ [ ] ] these brackets . [ [ aaaaa ] ] - > aaaaaMy python code ( using re library ) wasWhat if I want to extract only ' a ' from [ [ a|b ] ] Any concise regular expression for this task ? ( extract data before | ) Or should I use additional if statement ? <code> la = re.find... | Python regex partial extract |
Python : Am trying to sort big number strings in Python without converting the strings to integers and could n't understand how these lambda expression are evaluated.The first lambda expression is sorting based on length of string and sorting the list , but what does the second one do ? I would like to know how the sec... | How does this lambda for sorting numbers work ? |
Python : The problemI have a dataframe , with a certain number of observations as columns , measurements as rows . The results of the observations are A , B , C , D ... . It also has a category column , which denote the category of the measurement . Categories : a , b , c , d ... . If a column contains a nan in a row ,... | How to count the number of rows containing both a value in a set of columns and another value in another column in a Pandas dataframe ? |
Python : I am interested in learning the rationale behind the following behaviour : In Ruby , In Javascript : Clojure : While in Python : I would like to know why Python 's ( default ) behaviour is to raise an exception instead of returning some form of nil like the other languages listed above . I did n't see the answ... | Why do some languages return nil when a key is not in a dictionary , while Python throws an exception ? |
Python : In this code what is the purpose of the statements ( fix_imports ) and ( app ) ? This is the whole file : <code> from ferris import fix_imports ( fix_imports ) # Import the applicationfrom ferris.core import settingssettings.load_settings ( ) import ferrisimport ferris.appimport ferris.deferred_appimport ferri... | In Python what is the significance of parentheses , in isolation , surrounding a module name ? |
Python : If I make a deeply nested list , like this : thenwill work fine , butfails miserably with maximum recursion depth exceeded . ( `` % s '' % arr , and repr ( arr ) too . ) How could I get the string that print prints ? And what is the underlying reason for the difference ? <code> arr = [ 1 ] for i in range ( 100... | How to convert a deeply nested list to a string |
Python : I have went through multiple solutions on the net , but they require a lot of code that might get confusing once you scale up . Is there a simple way to stop the thread and avoid the RuntimeError : threads can only be started once , in order to call the thread an infinite number of times . Here is a simple ver... | What is the best way to stop a thread and avoid 'RuntimeError ' in python using threading and tkinter modules ? |
Python : Given : I would like to get the maximum subset ( in this case , the first row ) : By using print ( np.amax ( a , axis=0 ) ) , I 'm getting the wrong result : How can we get the correct maximum subset ? <code> a=np.array ( [ [ -0.00365169 , -1.96455717 , 1.44163783 , 0.52460176 , 2.21493637 ] , [ -1.05303533 , ... | Get maximum subset in multidimensional array |
Python : Consider the following Models in Django : The price of an item can vary throughout time so I want to keep a price history.My goal is to have a single query using the Django ORM to get a list of Items with their latest prices and sort the results by this price in ascending order.What would be the best way to ac... | Django queryset order by latest value in related field |
Python : I am trying to sum two columns of the DataFrame to create a third column where the value in the third column is equal to the sum of the positive elements of the other columns . I have tried the below and just receive a column of NaN valuesDataFrame : <code> df = pd.DataFrame ( np.array ( [ [ -1 , 2 ] , [ -2 , ... | How to create sum of columns in Pandas based on a conditional of multiple columns ? |
Python : I have a DataFrame like this : What I 'm trying to do is get a list of all the possible paths from a starting point , like 1 , and an ending point , like 6 , using the operators and nextvals , not strictly the shortest path.The output can be flexible , but I 'm looking for something like this or that communica... | Recursive Operation in Pandas |
Python : Because an algorithm I want to implement uses indices 1..n and because it 's very error prone to shift every index by one , I decided to get smart and inserted a dummy element in the beginning of every list , so I can use original formulas from the paper . For the sake of shortness , consider this toy example ... | PyPy : Severe performance penalty when using None in a list with integers |
Python : I 'm trying to reshape an array from its original shape , to make the elements of each row descend along a diagonal : I would like the result to look like this : This is the closest solution I 've been able to get : From here I think it might be possible to remove all zero diagonals , but I 'm not sure how to ... | Delete diagonals of zero elements |
Python : I have a pandas dataframe that represents a shift schedule for an entire year , given as : Where 1 represents Day shift ( 06:00 - 18:00 ) , 2 represents Night shift ( 18:00 - 06:00 ) and 0 can be ignored . Only a single shift team will be working for a given period.I need the data in a format where the data is... | What is an efficient pandas method to reindex this shift schedule ? |
Python : I was learning about classes and objects in Python when I came across this dilemma . Below are two cases of the same code , one without @ classmethod and the other with @ classmethod : As you can see that when not using @ classmethod , the name does n't change from Rounak to Agarwal . I do n't seem to understa... | How is the usage of @ classmethod causing difference in outputs ? |
Python : I am working on a Python script which queries several different databases to collate data and persist said data to another database . This script collects data from potentially millions of records across about 15 different databases . To attempt to speed up the script I have included some caching functionality... | How to forcibly free memory used by dictionary ? |
Python : I have attached a screenshot to help explain . I have a dataframe pulled from cleveland heart dataset that takes 76 columns and puts them into 7 columns and wraps the additional columns into the next row . I am trying to figure out how to get that dataframe into a readable format as shown in the dataframe on t... | Python - Transform dataframe and slicing |
Python : Why is the output of hashlib.md5 ( ) .hexdigest ( ) different than md5sum and openssl output ? I noticed this while trying to generate an md5 digest for use with Gravatar . The Python hashlib output works but the md5sum and openssl outputs do not . <code> $ echo `` test string '' | md5sumf299060e0383392ebeac64... | What is the difference between md5sum output and Python hashlib output ? |
Python : I want to insert a new column called total in final_dfwhich is a cumulative sum of value in df if it occurs between the times in final_df . It sums the values if it occurs between the start and end in final_df . So for example during the time range 01:30 to 02:00 in final_df - both index 0 and 1 in df occur be... | Pandas cumulative sum if between certain times/values |
Python : I saw that sometimes there are raised classes and sometimes there are raised instances of classes.Which way to raise exception is better if you do n't want to add any additional info as argumentsor ? <code> raise ValueError raise ValueError ( ) | Raise class exception or instance of class exception when no arguments are passed |
Python : The SQL command BETWEEN only works when I give it a small range for column . Here is what I mean : My code : Which corresponds to SQL command : and select_data returns a 2-D array containing all these rows.The column I am referencing here has already saved all values equal to 5.0.This Works FINE ! But , when I... | SQL BETWEEN command not working for large ranges |
Python : I used to show something like print ( 5 is 7 - 2 , 300 is 302 - 2 ) in my Python talks when talking about some Python trivia . Today I realised that this example yields a ( to me ) unexpected result when ran in Python 3.7.We know that the numbers from -5 to 255 are cached internally Python 3 docs - PyLong_From... | Cached integers , the ` is ` operator and ` id ( ) ` in Python 3.7 |
Python : For now I have something in my code that looks like this : f is actually a more complex function and it fails for specific values in an unpredictible manner ( I ca n't know if f ( x ) will fail or not before trying it ) .What I am interested in is to have this result : the list of all the valid results of f.I ... | Is there a more elegant way to filter the failed results of a function ? |
Python : SetupA dictionary of the following structural form : Expected OutputA Pandas DataFrame following the below schema : Working solution : My current approach works , but I wonder if there 's a cleaner solution ? <code> subnetwork_dct = { 518418568 : { 2 : ( 478793912 , 518418568 , 518758448 ) , 3 : ( 478793912 , ... | Dual nested dictionary to stacked DataFrame |
Python : I have two lists : I want to merge them , either to create a new list or just update a , by filling in the Nones with the values from b , soWhat 's the most efficient way of doing this ? For extension , I 'll be wanting to do this with every permutation of b . Does this allow shortcutting the technique at all ... | Merge list into sparse list efficiently |
Python : My dataframe : I would like to create a new data frame containing only the values in Font that belong to 3 unique maximum values . For example , 3 Maximum Font values for Input 133217 are 30 , 25 , 21.Expected output : I 've tried this with groupby from pandas : then I considered 1,2,3 values in df [ 'order ' ... | Group and find all values that belong to n unique maximum values |
Python : I want to pass a method as an argument that will call such method from another python file as follows : file2.pymain.pyWhat I expect is to return success.If calling a method within the same file ( main.py ) , I notice it is workable . However , for case like above where it involves passing an argument to be ca... | Python - How to pass a method as an argument to call a method from another library |
Python : I am new to metaclasses , and may be using them in unintended ways . I 'm puzzled by the fact that the isinstance ( ) method appears to have transitive behavior when dealing with subclasses , but not when dealing with metaclasses.In the first case : implies that isinstance ( ic , X ) is true for X equal to A ,... | Why is python isinstance ( ) transitive with base classes and intransitive with metaclasses ? |
Python : I have a Ruby function code block in multiple files that I need to change in each file.The function that I am trying to replace looks something like this : Each file has other functions in it but with different names . In some files I may have multiple tabs or spaces before.I want to replace the func1 in each ... | Replace a function block in a file using python |
Python : nargs='+ ' does n't work the way I expected : I can `` fix '' this by using -- name foo bar , but that 's unlike other tools I 've used , and I 'd rather be more explicit . Does argparse support this ? <code> > > > import argparse > > > parser = argparse.ArgumentParser ( ) > > > parser.add_argument ( `` -- nam... | How to use ` -- foo 1 -- foo 2 ` style arguments with Python argparse ? |
Python : I have a dict check_dict with keys and values . And another list input_list with keys.I 'm trying to make keys in check_dict to true whose keys are present in input_list.Expected output : <code> input_list = [ 'name ' , 'phone ' ] check_dict = { 'name ' : False , 'phone ' : False , 'address ' : False } final_d... | Python : Change values in a dict based on list ? |
Python : I have the following numpy structured array : As you can see , field 'f4 ' is a matrix : My end goal is to have a numpy structured array that only has vectors . I was wondering how to split 'f4 ' into two fields ( 'f41 ' and 'f42 ' ) where each field represents the column of the matrix.Also i was wondering if ... | Splitting numpy array field values that are matrices into column vectors |
Python : consider array1 and array2 , with : Both arrays are numpy-arrays . There is an easy way to compute the Euclidean distance between array1and each row of array2 : What messes up this computation are the NaN values . Of course , I could easily replace NaN with some number . But instead , I want to do the followin... | Calculate distance between arrays that contain NaN |
Python : I have a DataFrame : I could use list to aggregate the columns : What if I wanted to obtain an aggregate grouped by key1 , where each row is a dict of { key2 : value } pairs ? My expected output is : How can this be achieved in pandas ? One solution could be to create two lists using the function above and the... | Use dict aggregation in Pandas DataFrame |
Python : I am newbie in Python . I have a list of dictionary which look like as belowI want to convert this list into lists of list on the basic of common key2-id , The resultant list will look likeI have tried to accomplish this using gropby from itertool as below : It does n't give the result that I want . Its output... | How to do grouping of list of dictionary in Python ? |
Python : Consider an array with entries consisting exclusively of -1 or 1 . How do I get the ranges of all slices containing 1 exclusively and being of minimum length t ( e.g . t=3 ) Example : Then , desired output fort=3 would be [ ( 2,7 ) , ( 11,15 ) ] . <code> > > > a=np.array ( [ -1 , -1,1,1,1,1,1 , -1,1 , -1 , -1,... | getting ranges of sequences of identical entries with minimum length in a numpy array |
Python : I have a list of lists : I store the address of one of the inner lists in a variable : And now I expect to be able to retrieve the index of c ( =4 ) in this way , but it does n't work : The above works when the list contains constants , but it is n't working above . What am I missing ? <code> > > > a = [ list ... | Index of an inner list in a list of lists |
Python : I want the 5th subplot to be in the centre of the two columns in the third row . ( I have tried doing that by adding the domain argument ) . Here is the code to reproduce it-If I do not include the 6th plot in the specs argument , it throws an error . <code> import pandas as pdimport plotly.graph_objects as go... | Plotly : How to create an odd number of subplots ? |
Python : Help ! I have the following 2 models : Example : VisualizationMy problem : I want `` Deposits.user '' to automatically reference the user to which this 'receiveaddress ' belongs . In the example , that 's TIM . I 've wasted 6 hours trying to figure it out , what am I doing wrong ? Thanks in advance . <code> cl... | Django : Reference between models |
Python : With the type hinting syntax specified in PEP 484 and 585 , is there any way to indicate that a function 's parameter should be a mutable reference that would be modified by the function ? For instance , C # has ref paramters , so in Python , is there any equivalent ? e.g.or if not , how could I define such a ... | Indicating that a parameter should be a mutable reference |
Python : I have a CSV file that I need to loop through in a specific pattern for specific columns and have the output patterns be stored in new files with the same name + `` _pattern '' + [ 1,2,3 , etc . ] + .csv.This is the search pattern : Loop through column 1 and find the same # and grab them , then loop through co... | Python searching through columns |
Python : I have as input a csv file of the following format : I 'm trying to create a data structure where I can use the process id as an has key for all the entries of csv that match it . See the code below.My problem is that using this I do n't get a list of rows under the key , but only the last value I put there . ... | How to add a list under a dictionary ? |
Python : I plotted the frequency domain ( Fourier spectrum ) of an ECG signal.There is a high 0 Hz peak ( baseline wander ) and high 50 Hz peak ( net power ) . So I would like to filter with a band pass 5 - 49 Hz.raw_data = data ( y-axis ) and t = time ( x-axis ) After trying this code , it does n't filter like it need... | Bandpass filter after frequency domain fft |
Python : My apologies for a completely newbie question . I did try searching stackoverflow first before posting this question.I am trying to learn regex using python from diveintopython3.net . While fiddling with the examples , I failed to understand one particular outputfor a regex search ( shown below ) : Why does th... | Python regex explanation needed - $ character usage |
Python : On the one hand , I have learned that numbers that can be int or float should be type annotated as float ( sources : PEP 484 Type Hints and this stackoverflow question ) : On the other hand , an int is not an instance of float : issubclass ( int , float ) returns Falseisinstance ( 42 , float ) returns FalseI w... | Why does a type hint ` float ` accept ` int ` while it is not even a subclass ? |
Python : I have the following functions defined . For some reason , stack_data ( ) always returns an empty array and I can not figure out why . Does anyone have any suggestions ? General suggestions on improving coding style , form , readability , etc . would be very helpful . General debugging tips would be great too.... | Why is stack_data ( ) returning an empty array ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.