text
stringlengths
46
37.3k
title
stringlengths
12
162
Python : I wish to drop rows where the rows just before and just after has the same value for the column num2.My dataframe looks like this : And this is my target : What I have tried : Giving : And I was thinking to use the new num1_diff column to do the filtering.Is this a good approach , or is there perhaps a better ...
Conditionally drop Pandas Dataframe row
Python : I am searching a string by using re , which works quite right for almost all cases except when there is a newline character ( \n ) For instance if string is defined as : Then searching like this re.search ( 'Test ( . * ) print ' , testStr ) does not return anything.What is the problem here ? How can I fix it ?...
Splitting a string by using two substrings in Python
Python : I am using the wave library in python to attempt to reduce the speed of audio by 50 % . I have been successful , but only in the right channel . in the left channel it is a whole bunch of static.why is this ? since I am just copying and pasting raw data surely I ca n't generate static ? edit : I 've been looki...
my program reduces music speed by 50 % but only in one channel
Python : How I can do for do this code efficiently ? I think must be a efficient way to do this with a numpy library ( without loops ) . <code> import numpy as nparray = np.zeros ( ( 10000,10000 ) ) lower = 5000 higher = 10000 for x in range ( lower , higher ) : for y in range ( lower , higher ) : array [ x ] [ y ] = 1...
Assign values to array efficiently
Python : Here is an simple example that gets min , max , and avg values from a list.The two functions below have same result.I want to know the difference between these two functions . And why use itertools.tee ( ) ? What advantage does it provide ? <code> from statistics import medianfrom itertools import teepurchases...
tee ( ) function from itertools library
Python : Suppose we have a class we want to monkeypatch and some callables we want to monkeypatch onto it.Even though baz is a callable , it does n't get bound to a Foo ( ) instance like the two functions bar and wrapped_baz . Since Python is a duck-typed language , it seems strange that the type of a given callable wo...
Why do n't non-function callables get bound to class instances ?
Python : QuestionI have a dataframe untidywhere the values in the 'attribute ' column repeat periodically . The desired output is tidy ( The row and column order or additional labels do n't matter , I can clean this up myself . ) Code for instantiation : AttemptsThis looks like a simple pivot-operation , but my initial...
Pivot a two-column dataframe
Python : I was going through the topic about list in Learning Python 5E book.I notice that if we do concatenation on list , it creates new object . Extend method do not create new object i.e . In place change . What actually happens in case of Concatenation ? For exampleAnd if I use Augmented assignment as follows , Wh...
Python Lists : Why new list object gets created after concatenation operation ?
Python : I 'm trying not to use lambda here because of it 's performance issues in loops , I know there 's uses for lambda but I find this one should have a better alternative.Original code : this works but I do n't like that lambda there.I have tried the following : I must be missing something small here that will mak...
itertools.accumulate but trying to replace lambda with str.join
Python : Say I have a list of names in python , such as the following : names = [ 'Alice ' , 'Bob ' , 'Carl ' , 'Dave ' , 'Bob ' , 'Earl ' , 'Carl ' , 'Frank ' , 'Carl ' ] Now , I want to get rid of the fact that there are duplicate names in this list , but I do n't want to remove them . Instead , for each name that ap...
Labeling duplicates in a list
Python : As per the official python tutorial , In interactive mode , the last printed expression is assigned to the variable _ . This means that when you are using Python as a desk calculator , it is somewhat easier to continue calculations , for example : This variable should be treated as read-only by the user . Don ...
Is it acceptable to use underscore as a loop variable in python ?
Python : For some reasons python gets variable from global namespace when situations like this occurs : Please look at this code : In accordance with PEP 227 A class definition is an executable statement that may contain uses and definitions of names . These references follow the normal rules for name resolution . The ...
Variable scopes inside class definitions are confusing
Python : I have the below data.. where you can see spaces between 2 lines in the beginning and no spaces in between some other lines : I need the final output as this : I have tried using output = `` `` .join ( line.strip ( ) for line in f ) but it doesnt work as I need . this is my output : all the lines in a single l...
joining only lines with spaces in python
Python : I have two lists in python , which stores some class instances in different manners ( e.g . order ) . Now , I would like to create a copy of these two lists for some purpose ( independent from the existing ones ) . To illustrate my problem clearly , I created a demo code below.By using deepcopy operation , I c...
Deepcopy of two lists
Python : Let 's say I want a custom frozenset with 2 elements , that iterates , hashes , compares , and has various other nice operations as a frozenset , but prints differently . I can inherit , or I can delegate , but in neither case I get what I want.If I inherit literally , there seems to be no way I can write __in...
Customizing immutable types in Python
Python : I have three strings which have information of the street name and apartment number . `` 32 Syndicate street '' , `` Street 45 No 100 '' and `` 15 , Tom and Jerry Street '' Here , I am trying to use Python 's regex to get the street names and apartment numbers separately.This is my current code , which is havi...
Python regex compile and search strings with numbers and words
Python : I want to convert a pandas Series of strings of list of numbers into a numpy array . What I have is something like : My desired output : What I have done so far is to convert the pandas Series to a Series of a list of numbers as : but I do n't know how to go from ds1 to arr . <code> ds = pd.Series ( [ ' [ 1 -2...
Convert a pandas Series of lists into a numpy array
Python : Take the following toy DataFrame : I 'd like to replace the `` year '' columns ( 2014-2017 ) with two fields : the most recent non-null observation , and the corresponding year of that observation . Assume field1 is a unique key . ( I 'm not looking to do any groupby ops , just 1 row per record . ) I.e . : I '...
Getting most recent observation & date from several columns
Python : When you start your Python interpreter it appears that some modules/packages are automatically imported during the startup process : However , these modules seem to have been loaded into a different scope/namespace because you ca n't access them without an additional import : Here are my questions : What preci...
Why ca n't you reference modules that appear to be automatically loaded by the interpreter without an additional ` import ` statement ?
Python : How would you compare two ( or more columns ) values ONLY if another column value is True.Ideally , the output would just be True ( if everything is matching correctly ) False otherwise.Something like that : df [ 'value1 ' ] .equals ( df [ 'value2 ' ] ) but only if df [ 'isValid ' ] is true.Sorry if this is a ...
Compare two or more columns values only if another column value is True
Python : I have a data frame similar to the followingI want to create a data frame using this so that the resulting table shows the count of each category in class per yer.What 's the easiest way to do this ? <code> + -- -- -- -- -- -- -- -- + -- -- -- -+| class | year |+ -- -- -- -- -- -- -- -- + -- -- -- -+| [ ' A ' ...
Pandas groupby for multiple values in a column
Python : Why does the example below only work if the useless _ variable is created ? The _ variable is assigned and never used . I would assume a good compiler would optimize and not even create it , instead it does make a difference.If I remove _ = and leave just Test ( ) , then the window is created , but it flickers...
Why do I need to keep a variable pointing to my QWidget ?
Python : I 'm trying to show difference between bars using annotation . Specifically , showing difference between all bars with respect to the first bar.My code is shown below : The result graph looks like : As you can see , I 'm trying to use annotation to indicate the difference between a and b . But I do n't know ho...
How to annotate difference between bars ?
Python : How to filter the rows in a data frame based on another column value ? I have a data frame which is , Based on the column values of `` min_subject '' and `` min_marks '' , the row should be filtered . For index 0 , the `` min_subjects '' is `` 2 '' , at least 2 elements in `` marks '' column should be greater ...
Pandas : filter the rows based on a column containing lists
Python : Current StatusI have an abstract base class that , which hosts data in the form of a numpy array , knows how to work this data , and which can explain matplotlib how to draw it . To accomodate different types of data , it has a number of subclasses , like this : The Issuenow , the issue is how to get the class...
Calling class method as part of initialization
Python : I 'm trying to parse output from OS X 's mdls command . For some keys , the value is a list of values . I need to capture these key , value pairs correctly . All lists of values start with a ( and then end with a ) . I need to be able to iterate over all the key , value pairs so that I can properly parse multi...
Efficiently replace multi-line list strings with single_line list string
Python : I have a dictionary ( multidimensional ? ) like this : I would like to find any duplicate matching position ( 0 ) or ( 1 ) value in the dictionary lists and if there is a duplicate then reverse the second matching pair of numbers.The dictionary would become : Only position ( 0 ) would be a duplicate of positio...
How to reverse duplicate value in multidimensional array
Python : I noticed that passing Python objects to native code with ctypes can break mutability expectations.For example , if I have a C function like : and I call it like this : The value of s changed , and is now b '' Xsdf '' .The Python docs say `` You should be careful , however , not to pass them to functions expec...
Python ctypes and mutability
Python : Df1 : Df2 : Required : I have these df1 and df2 and I want to get the required df where common Ids present in Df1 and Df2 will get updated , and new Ids will get appended.I dont seem to find if I need to use update , merge or join or something else . <code> Id val1 43 79 24 5 Id val1 57 2 Id val1 53 79 24 57 2
Update dataframe based on index and append the new ones
Python : My code looks something like this : My question is whether LARGE_MODEL will be pickled/unpickled with each iteration of the loop . And if so , how can I make sure each worker caches it instead ( if that 's possible ) ? <code> from joblib import Parallel , delayed # prediction model - 10s of megabytes on diskLA...
How does joblib.Parallel deal with global variables ?
Python : I have three datasets ( final_NN , ppt_code , herd_id ) , and I wish to add a new column called MapValue in final_NN dataframe , and the value to be added can be retrieved from the other two dataframes , the rule is in the bottom after codes.final_NN : ppt_code : herd_id : Expected output : The rules is : if n...
A better way to map data in multiple datasets , with multiple data mapping rules
Python : Let 's say I have a function : I can create a higher-order function that behaves like so : And then augment ( f ) ( 1 ) will return { `` x '' : 1 , `` metadata '' : `` test '' } .But what if f is an async coroutine , this augment function does not work ( RuntimeWarning : coroutine ' f ' was never awaited and T...
Higher-order function on async coroutine
Python : What 's the deal ? Yes , b.dtype == 'float64 ' , but so are its slices b [ 0 ] & b [ 1 ] , and a remains 'float32'.Note : I 'm asking why this occurs , not how to circumvent it , which I know ( e.g . cast both to 'float64 ' ) . <code> import numpy as npa = np.array ( [ .4 ] , dtype='float32 ' ) b = np.array ( ...
Different slices give different inequalities for same elements
Python : I want to download all the python packages mentioned in the requirement.txt to a folder in Linux . I do n't want to install them . I just need to download them.python version is 3.6list of packages in the requirement.txt <code> aiodns==0.3.2aiohttp==1.1.5amqp==1.4.7anyjson==0.3.3astroid==1.3.2asyncio==3.4.3asy...
how to download all the python packages mentioned in the requirement.txt to a folder in linux ?
Python : My path : I want this to be converted into : How to do this ? <code> '/home//user////document/test.jpg ' '/home/user/document/test.jpg '
How to replace multiple forward slashes in a directory by a single slash ?
Python : Somehow after doing this suddenly id ( list2 ) ==id ( list1 ) evaluated to True ? What on earth is happening ? while the loop is running this does not seem to bee the case the first output is as expected :0 10 , 1 11 , 2 12 , ... 0 0 , 1 2 , 2 3 , ... the second though gives:0 0 , 1 1 , 2 2 ... How is this pos...
very wonderous loop behavior : lists changes identity . What is happening ?
Python : I am not sure how to do this but I believe is doable . I have three dataframes having the same column definition but dataset from different years . I then want to pairplot the numeric columns taking the columns one-by-one and plotting the data from these dfs appropriately labeling the set for which data comes ...
pairplot columns from multiple dataframes labelled by classes from the category column
Python : I 'm working on the following dataframe : and discovered this Relaxed Functional Dependency ( RFD ) : meaning that for each couple of rows having a difference < =2 on the weight they would have a difference < =1 on the height too.I need to find all the subsets of rows on which this RFD holds , and show the one...
how to get dataframe subsets having similar values on some columns ?
Python : My lecturer has set several questions on python , and this one has got me confused , I dont understand what is happening.Python tells me , after running this that x is [ [ ... ] ] , what does the ... mean ? I get even more confused when the result of the following is just [ [ ] ] If y is calculated to be [ [ ]...
Why does Python extend output [ [ ... ] ]
Python : I am very new to Python , trying to learn the basics . Have a doubt about the list.Have a list : The output should be : The code that works for me is the followingIt gives the output [ [ 2,4,6 ] , [ 8,10,12 ] , [ 6,8,12 ] ] .Now I want the same output with a different code : With the above code the output obta...
How to modify the elements in a list within list
Python : Consider the following function , whose output is supposed to be the cartesian product of a sequence of iterables : Works fine when generator comprehensions are replaced with list comprehensions . Also works when there are only 2 iterables . But when I tryI get Why this and not the cartesian product ? <code> d...
Why doesnt my cartesian product function work ?
Python : I have a .txt file that looks like the s string . The s string is conformed by word_1 followed by word_2 an id and a number : I would like to create a regex that catch in a list all the ocurrences of the word `` nunca '' followed by the id VM_ _ _ _ . The constrait to extract the `` nunca '' and VM_ _ _ _ patt...
How to fix a regex that attemps to catch some word and id ?
Python : I have a dataframe which looks like thisI want to calculate the weighted mean by group in column ' B ' ignoring the min and max value ( column ' V ' ) wherecolumn W = weightcolumn V = valueTo calculate the simple mean for each group considering all values I can do this : However , I want to ignore the max and ...
How to ignore min & max value in group when calculating weighted mean by group in Pandas
Python : I import an image from file and that file always updates ( always save the new picture in the same file name ) and now when that image change in file My GUI not update must change page or do something that image will change I mean change on display . But I would like image change on display in real-time ( chan...
How to update image file realtime Pygame ?
Python : This is an old-style class : This is a new-style class : This is also a new-style class : Is there any difference whatsoever between NewStyle and NewStyle2 ? I have the impression that the only effect of inheriting from object is actually to define the type metaclass , but I can not find any confirmation of th...
Is subclassing from object the same as defining type as metaclass ?
Python : I am trying to call a function in an if , save the value in a variable and check if the value is equal to something.Have tried : I am getting a syntax error . Can this be done ? I 'm coming from C and I know that this can work : Is this possible in python ? P.S . The functions are simple so it is easier to und...
Defining variable in if
Python : I have a dataframe as follows : What I want to do here is to create two new columns 'min ' and 'max ' , such that 'min ' outputs the last possible slot with time < last ; and 'max ' outputs the last possible slot with time < next.The desired output here should be : I tried something along the lines ofbut got a...
Finding last possible index value to satisfy filtering requirements
Python : I have an array of strings : I want to obtain : I tried : Does n't work because I need s. in front and , at the end <code> data = [ ' a ' , ' b ' , ' c ' , 'd ' ] s.a , s.b , s.c , s.d `` s. , `` .join ( fields )
String concatenation from a list of string , using a praticle in front and one at the end for each element
Python : I have a dataframe as given belowHow to combine two columns in above df into a single list such that first row elements come first and then second row . My expected outputMy code : This did not work ? <code> df = index data1 data20 20 1201 30 4562 40 34 my_list = [ 20,120,30,456,40,34 ] list1 = df [ 'data1 ' ]...
Python how to combine two columns of a dataframe into a single list ?
Python : My code : First , I click Connect button . It 's worked , but when I click Turn left or Turn right , I got an error : <code> class Receiver ( QWidget ) : def __init__ ( self ) : self.s = socket.socket ( socket.AF_INET , socket.SOCK_STREAM ) # Create button QToolTip.setFont ( QFont ( 'Time New Roman',10 ) ) sup...
Bad file descriptor when using Pyside
Python : I was going through the code for six.py in the django utils , which , for non Jython implementations , tries , to find the MAXSIZE for the int . Now , the way this is done is interesting - instead of catching an exception on the statement itself , the statement is wrapped within a __len__ method in a custom cl...
Why does six.py use custom class for finding MAXSIZE ?
Python : Imagine this is a part of a large text : stuff ( word1/Word2/w0rd3 ) stuff , stuff ( word4/word5 ) stuff/stuff ( word6 ) stuff ( word7/word8/word9 ) stuff / stuff , ( w0rd10/word11 ) stuff stuff ( word12 ) stuff ( Word13/w0rd14/word15 ) stuff-stuff stuff ( word16/word17 ) .I want the words . The result must ma...
Regex to match all words inside parenthesis
Python : I 'm trying to merge two series with mismatching indicies into one , and I 'm wondering what best practices are . I tried combine_first but I 'm getting an issue where combining a series [ 0 , 24 , ... ] with a series [ 1 , 25 , ... ] should give a series with indicies [ 0 , 1 , 24 , 25 , ... ] but instead I '...
Combining two series into one with mismatching indicies
Python : I am trying to create a class called PolyExt which is an extension of the Poly class in SymPy . And , it has its own __init__ method . But the problem is that when it passes through the __new__ method in the inherited Poly class , the extra arguments that I added to the __init__ method get interpreted as part ...
How to add arguments to a class that extends ` Poly ` class in sympy ?
Python : I have a dict which goes something like this : I need to find which of the items in the value sets have maximum number of keys against them and also have the items listed in descending order . The output will be something like : But I read somewhere that the dict can not be in a sorted fashion , so the output ...
Identifying the values which have the maximum number of keys
Python : My first day in Python and get confused with a very short example . Hope anyone can provide some explanation about why there is some difference between these several versions . Please ! V1 : the output is 1 , 1 , 2 , 3 , 5 , 8V2 : the output is 1 , 2 , 4 , 8 <code> a , b = 0 , 1while b < 10 : print ( b ) a , b...
Python multiple variable assignment confusion
Python : I 'm learning about decorators and came across an example where the decorator took an argument . This was a little confusing for me though , because I learned that ( note : the examples from this question are mostly from this article ) : was equivalent to So , it does n't make sense to me how something could t...
What is the equivalent of decorators with arguments without the syntactical-sugar ?
Python : I want to find the highest 3 values of each column in a dataframe , and return the index names , ordered by value . The dataframe looks like this : The result would look like this : <code> df = pd.DataFrame ( { `` u1 '' : [ 1,2 , -3,4,5 ] , `` u2 '' : [ 8 , -4,5,6,7 ] , `` u3 '' : [ np.NaN , np.NaN , np.NaN , ...
Finding highest n values of every column in dataframe
Python : My string contains text = `` a ) Baghdad , Iraq b ) United Arab Emirates ( possibly ) '' I want to split this in list like [ `` Baghdad , Iraq '' , '' United Arab Emirates ( possibly ) '' ] The code which i have used is not providing me the desired resultPlease help me regarding this <code> re.split ( '\\s* ( ...
Split string into list contains alphabetical bullet list
Python : Consider the following example : Output : I would expected the same output if enumerate is called outside the list comprehension and the iterators are assigned to variables : But I get : What is going on ? I use Python 3.6.9 . <code> s = 'abc ' [ ( c1 , c2 ) for j , c2 in enumerate ( s ) for i , c1 in enumerat...
Multiple iterators ( using enumerate ) for the same iterable , what is going on ?
Python : Found the following code in a book but could n't get the complete explanation.The python code in the first case is creating an array of 1000000 lengths while in the 2nd part is creating a single size array and multiplying the size by the same factor.The code in the 2nd case is 100 times faster than the first c...
Why is it more efficient to create a small array , and then expand it , rather than to create an array entirely from a large list ?
Python : If I do something like this : There is no error , I just replaced the get method.But if I do a : I get : This is strange because the source code is readable at /usr/lib/python3.6/datetime.py.I guess this library has been compiled for performance reason , that is why it can not be modified . But , then , the qu...
How to check if a function/method/class is built-in Python ?
Python : I have a table of data with a multi-index . The first level of the multi-index is a name corresponding to a given sequence ( DNA ) , the second level of the multi-index corresponds to a specific type of sequence variant wt , m1 , m2 , m3 in the example below . Not all given wt sequences will have all types of ...
Filter a pandas data frame by requiring presence of multiple items in a MultiIndex level
Python : I am able to select columns of a Pandas DataFrame with their positions : With this , I can select the columns b up to d.Is there any easy way I can do this using the column names ? Something like : <code> df = pd.DataFrame ( { `` a '' : [ 1 , 2 , 3 ] , `` b '' : [ 4 , 5 , 6 ] , `` c '' : [ 7 , 8 , 9 ] , `` d '...
Python Pandas : Selection of Columns by Column Names
Python : I got this : So in this case Why is <code> # slicing : [ start : end : step ] s = ' I am not the Messiah ' # s [ 0 : :-1 ] = ' I ' start=0 , end=0 , step=-1 s [ 0 : :-1 ] == ' I ' > > > > True
Why is that slicing expression generating that output
Python : So I was trying to make something that resembles fireworks . I made a particle class , which will make up the fireworks.Then I made a Fireworks class which shoots particles from 0 to 360 degrees.Now I want to draw a line from the position they spawn ( 600 , 300 ) , along the path the particles take . But the t...
Drawing a line between points in pygame
Python : If I have a list as such : How would you get that in a single string that states Is there a simpler way than <code> arr = [ [ `` Hi `` , `` My `` , `` Name `` ] , [ `` Is `` , `` Sally . `` , `` Born `` ] , [ 3 , 13 , 2010 ] ] H , My Name Is Sally . Born 3 13 2010 example = `` '' for x in range ( len ( arr ) )...
How to append list of numerous types to single string ( python )
Python : Given a class or function , is there a way to find the full path of the module where it is originally defined ? ( I.e . using def xxx or class xxx . ) I 'm aware that there is sys.modules [ func.__module__ ] . However , if func is imported in a package 's __init__.py , then sys.modules will simply redirect to ...
Getting a function 's module of original definition
Python : I would have hoped this works ( in Python 3.6 ) , but I get Surprisingly , works as hoped . <code> class A : __hash__ = idA ( ) .__hash__ ( ) TypeError : id ( ) takes exactly one argument ( 0 given ) def my_id ( self ) : return id ( self ) class A : __hash__ = my_idA ( ) .__hash__ ( )
Why can I not assign ` cls.__hash__ = id ` ?
Python : Python supports creating properties `` on the fly '' , like so.But this is a tad ugly . I have to have some instruction within the class , either a function or a class property definition.But the main hindrance is this ... And it raises because first does n't exist , obviously . I would have to do something li...
How can I recursively create class properties in Python ?
Python : Consider this statement : However : It is incredible . What 's the reason and the interpretation ? <code> > False == False in [ False ] True > ( False == False ) in [ False ] False > False == ( False in [ False ] ) False
How can an expression be different from however paarenthesized ?
Python : I want to map a list or array into an array in python 3.x , input a [ a , b , c ] and get result like [ a*2 , a*2+1 , b*2 , b*2+1 , c*2 , c*2+1 ] e.g : There must be better ways . Both list and numpy solutions will be ok . Thanks <code> a = np.array ( [ 2,4,6 ] ) result = [ ] for a1 , a2 in zip ( a*2 , a*2+1 )...
Map python array into a x times longer array using each element x times
Python : I have a large dataframe containing a column titled `` Comment '' within the comment section I need to pull out 3 values and place into separate columns i.e . ( Duty cycle , gas , and pressure ) `` Data collection START for Duty Cycle : 0 , Gas : Vacuum Pressure : 0.000028 Torr '' Currently i am using .split a...
How to select values in between strings and place in column of dataframe using regex in python
Python : Is there any good reason why one would assign a class to a variable as shown in the code below ? What are some useful/interesting things one can do thanks to that mechanic ? <code> class foo : # Some initialization stuff def __init__ ( self ) : self.x = 0 # Some methods and other stuffmyVar = foo
Uses of assigning a class to a variable in Python
Python : I am brand-new to web scraping and want to scrape the player name and salary from spotrac for a university project.What I have done to date is as below.The output of this is only 100 names , but the page has 1000 elements . Is there a reason why this is the case ? <code> import requestsfrom bs4 import Beautifu...
Beautifulsoup only returing 100 elements
Python : I want to remove the few words in a column and I have written below code which is working fine Now I have around 30 words to remove but I ca n't repeat this line of code 30 times Is there any way to solve my issue if yes please guide me <code> finaldata [ 'keyword ' ] = finaldata [ 'keyword ' ] .str.replace ( ...
Removing multiple phrases from string column efficiently
Python : I have a dataframe that have two values : What I am trying to do is to remove the numeric digits in case of the split ( ' _ ' ) only have numeric digits.The desired output is : For that I am using the following code : But it gives me the following output : How can do what I want ? Thanks ! <code> df = pd.DataF...
Python - Pandas - Remove only splits that only numeric but maintain if it have alphabetic
Python : I wish to add a new row in the first line within each group , my raw dataframe is : it is like this : For each person ( 'ID ' ) , I wish to create a new duplicate row on the first row within each group ( 'ID ' ) , the values for the created row in column'ID ' , 'From_num ' and 'To_num ' should be the same as t...
How to add a row to every group with pandas groupby ?
Python : Given a Pandas dataframe df , we can sum the columns like thisand produce the sum of sums like this.Can this be done using only dataframe operations , without resorting to Python 's sum ( ) ? <code> [ x for x in df.sum ( ) ] sum ( [ x for x in df.sum ( ) ] )
Pandas : Summing all elements in a dataframe ?
Python : If I do import A from within a directory containing both A.py and A.so , the .so file will be imported . I 'm interested in changing the order of import file types , so that .py takes precedence over .so , though only temporarily , i.e . between code line i and j . Surely this can be achieved through some impo...
Python : Changing precedence of import file types ( .py before .so )
Python : I was curious about how something worked in yum so I was looking at some of its score code and I found this line in the erasePkgs function in cli.py.The if False : pass does nothing correct ? It never gets into that branch it always just skips to the next one does n't it ? Here is the link to the source code :...
Useless if statement in yum source
Python : Using list comprehension I have created a list of tuples which looks likeI could also create a list of lists if that works easier.Either way , I would now like to get an array , or a 2D list , from the data . Something where I can easily access the value of the first element in each tuple in the above using sl...
Converting a list of tuples to an array or other structure that allows easy slicing
Python : I searched all over and could not come up with a reasonable search query to produce helpful results . I 'll try to explain this with a simple example ( that is tested ) .Suppose I have some small custom Python library that contains just the following private class and public instance of it : Now , I also have ...
Accessing a class instance in a library from two separate scripts in a project
Python : I 'm confused by the behaviour of type conversion when constructing a structured/recarray : This simple example takes in numerical fields but defines the type as string : Which produces : So the values were converted to empty strings which is not what you would expect from : Which produces the string ' 1.0 ' ....
python structured/recarray type conversion behaviour
Python : I have a pypi package called collectiondbf which connects to an API with a user entered API key . It is used in a directory to download files like so : I know this should be basic knowledge , but I 'm really stuck on the question : How can I save the keys users give me in a meaningful way so that they do not h...
How to have persistent storage for a PYPI package
Python : I have a matrix x with 3 x 3 dimensions and a vector w that is 3 , :I need to generate another vector y that is a majority vote for each row of x . Each column of x is weighted by the corresponding value in w. Something like this : for y [ 0 ] , it should look for X [ 0 ] = > [ 1 , 2 , 1 ] columns with value 1...
Return majority weighted vote from array based in columns
Python : My problem looks something like this.Then I call on the fields from another module . The class is initiated before and I call on the name field like this : Which gives : I do n't understand why it would be different values . Does anyone have any idea why this would happen ? Thanks for your time . <code> # Modu...
Accessing field : different value if its stored in a dict
Python : I 'm trying to set a default value for an argument in a function I 've defined . I also want another argument to have a default value dependent on the other argument . In my example , I 'm trying to plot the quantum mechanical wavefunction for Hydrogen , but you do n't need to know the physics to help me.where...
Setting argument defaults from arguments in python
Python : I have a sample DF , trying to replace the list of column values with ascending sorted index : DF : Step 1 : Step 2 : In this group , replace the values of columns [ `` d1 '' , '' d2 '' ] with index ( not the DF index ) of sorted mean values based on c.For example in the above group mean ( c , d1= '' Apple '' ...
Replace pandas column with sorted index
Python : I am trying to make a recursive merge sort function in python , however , my code would not work . It first splits the code into 1 cell arrays then merges and sorts them together . However , on the second level of the merge , the function reverts back to the arrays that have not been sorted . I was wondering h...
How to fix my merge sort because it reverts my arrays into unsorted ones ?
Python : What 's the approved programming pattern for distributing keyword arguments among called functions ? Consider this contrived ( and buggy ) example : Obviously the set_size ( ) method will object to receiving material or color keyword arguments , just as set_appearance ( ) will object to receiving width , heigh...
best way to distribute keyword arguments ?
Python : I would like to know how Python 3 ( not 2 , please : P ) address the following situation : I have a class and two instances : Do a.something and b.something share the same memory address , or each one have a something declared ? How the resolution of calling a.something works ? When I try to see the methods id...
Does different instances share the same methods declared in the class ?
Python : I have an input text which looks like this : I have to renumber word and bla from 1 , in each line.I can renumber the whole input which looks like this : The code for the above : Ideally , the result should look like this : <code> word77 text text bla66 word78 text bla67text bla68 word79 text bla69 word80 text...
Renumbering line by line
Python : Today I have started to learn Python . The first things I learned were values , expressions and ( arithmetic ) operators . So far , everything makes sense , except one thing that I don not get : Whileevaluates to 4 ( which makes sense ) , results in a SyntaxError ( which also makes sense ) . But what – from my...
Why can I repeat the + in Python arbitrarily in a calculation ?
Python : I 'm playing around with generators to better understand how they work , but I 'm confused with the result of the following piece of code : What 's going on here ? Looks like as it hits the `` for i in count : '' line the generator yields the first value . I 'm not sure . EDIT : I should add that I 'm not tryi...
Python Generator : confusing result
Python : I have a datframe as : For RES1 , I want to create a counter variable RES where COND ==1 . The value of RES for the first KEY of the group remains same as the VAL ( Can I use cumcount ( ) in some way ) . For RES2 , then I just want to fill the missing values asthe previous value . ( df.fillna ( method='ffill '...
How to create a increment var from a first value of a dataframe group ?
Python : I have a question about generators and/or python 's execution model.Given something like : My main confusion is : What happens to handle ifis called only once ? Does the handle stay open for the life of the program ? What if we have scarce resources being allocated in a generator body ? Threads ? Database hand...
Lifespan of open handles in a python generator body
Python : I have two dataframes where one contains pet ID 's and names , and the other user 's and a list of the ID 's of the pets they like . I 'd like to get this into a dict where the keys are users , and the values being all the names of the pets they like . <code> id name0 4 Bert1 5 Ernie2 6 Jeff3 7 Bob4 8 Puppy5 9...
Most efficient way to rename elements in dataframe of lists
Python : So , I wanted to try GCloud since you can deploy serverless stuff pretty easily . I 've made a simple Flask app to test it out , this is the entire code for the app : Here is the Dockerfile : I 've also tried using gunicorn and waitress to start the server , the same thing happens.Commands I run to deploy to g...
Cloud builds failing for super simple Flask app no matter what I do
Python : I often have statements in my code that do the following : which is very clear , but verbose and somewhat redundant at the same time . Is there any way in Python to simplify this statement perhaps by making some_function act as a `` mutating '' ( `` in-place '' ) function ? For example , in Julia one can often...
Mutating / in-place function invokation or adaptation in Python