lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
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 one ?
import pandas as pddf = pd.DataFrame ( [ [ 12 , 10 ] , [ 11 , 10 ] , [ 13 , 10 ] , [ 42 , 11 ] , [ 4 , 11 ] , [ 5 , 2 ] ] , columns= [ `` num1 '' , `` num2 '' ] ) df = pd.DataFrame ( [ [ 12 , 10 ] , [ 13 , 10 ] , [ 42 , 11 ] , [ 4 , 11 ] , [ 5 , 2 ] ] , columns= [ `` num1 '' , `` num2 '' ] ) df [ `` num1_diff '' ] = df...
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 ?
testStr = `` Test to see\n\nThis one print\n ``
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 looking for ag...
import wave , os , mathr=wave.open ( r '' C : \Users\A\My Documents\LiClipse Workspace\Audio compression\Audio compression\aha.wav '' , '' r '' ) w=wave.open ( r '' C : \Users\A\My Documents\LiClipse Workspace\Audio compression\Audio compression\ahaout.wav '' , '' w '' ) frames=r.readframes ( r.getnframes ( ) ) newfram...
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 ) .
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 print ( array )
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 ?
from statistics import medianfrom itertools import teepurchases = [ 1 , 2 , 3 , 4 , 5 ] def process_purchases ( purchases ) : min_ , max_ , avg = tee ( purchases , 3 ) return min ( min_ ) , max ( max_ ) , median ( avg ) def _process_purchases ( purchases ) : return min ( purchases ) , max ( purchases ) , median ( purch...
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 would play ...
class Foo : passdef bar ( *args ) : print ( list ( map ( type , args ) ) ) class Baz : def __call__ ( *args ) : print ( list ( map ( type , args ) ) ) baz = Baz ( ) def wrapped_baz ( *args ) : return baz ( *args ) Foo.bar = barFoo.baz = bazFoo.biz = wrapped_bazFoo ( ) .bar ( ) # [ < class '__main__.Foo ' > ] Foo ( ) .b...
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 approach...
attribute value0 age 491 sex M2 height 1763 age 274 sex F5 height 172 age sex height0 49 M 1761 27 F 172 untidy = pd.DataFrame ( [ [ 'age ' , 49 ] , [ 'sex ' , 'M ' ] , [ 'height ' , 176 ] , [ 'age ' , 27 ] , [ 'sex ' , ' F ' ] , [ 'height ' , 172 ] ] , columns= [ 'attribute ' , 'value ' ] ) tidy = pd.DataFrame ( [ [ 4...
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 , What is hap...
l = [ 1,2,3,4 ] m = ll = l + [ 5,6 ] print l , m # output ( [ 1,2,3,4,5,6 ] , [ 1,2,3,4 ] ) l = [ 1,2,3,4 ] m = ll += [ 5,6 ] print l , m # output ( [ 1,2,3,4,5,6 ] , [ 1,2,3,4,5,6 ] )
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 make me feel...
from itertools import accumulates = `` lorem ipsum dolor '' print ( list ( accumulate ( s.split ( ) , lambda x , y : f ' { x } { y } ' ) ) ) # [ `` lorem '' , `` lorem ipsum '' , `` lorem ipsum dolor '' ] print ( list ( accumulate ( s.split ( ) , ' '.join ) ) )
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 appears mor...
def mark_duplicates ( name_list ) : output = [ ] duplicates = { } for name in name_list : if name_list.count ( name ) = 1 : output.append ( name ) else : if name in duplicates : duplicates [ 'name ' ] += 1 else : duplicates [ 'name ' ] = 1 output.append ( name + `` _ '' + str ( duplicates [ 'name ' ] ) ) return output
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 ’ t expli...
> > > tax = 12.5 / 100 > > > price = 100.50 > > > price * tax12.5625 > > > price + _113.0625 > > > round ( _ , 2 ) 113.06 n = 42for _ in range ( n ) : do_something ( )
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 namespace...
class Cls : foo = foo foo = 'global'def func0 ( ) : foo = 'local ' class Cls : bar = foo print ( 'func0 ' , Cls.bar ) func0 ( ) # func0 localdef func1 ( ) : foo = 'local ' class Cls : foo = foo print ( 'func1 ' , Cls.foo ) func1 ( ) # func1 globaldef func2 ( ) : foo = 'nonlocal ' def internal ( ) : class Cls : foo = fo...
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 line..
Report AreaTotal PopulationTotal Land Area ( Square Miles ) Population Density ( Per Square Mile ) Report Area 37,325,068 155,738.02 239.67 Alameda County , CA 1,515,136 738.82 2,050.75 Alpine County , CA 1,197 738.13 1.62 Amador County , CA 37,764 594.43 63.53 Butte County , CA 220,101 1,636.03 134.53 Calaveras County...
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 created tw...
import copyclass Node : def __init__ ( self ) : self.node_id = 0node = Node ( ) list1 = [ node ] list2 = [ node ] u_list1 = copy.deepcopy ( list1 ) u_list2 = copy.deepcopy ( list2 ) id1 = id ( list1 [ 0 ] ) id2 = id ( list2 [ 0 ] ) u_id1 = id ( u_list1 [ 0 ] ) u_id2 = id ( u_list2 [ 0 ] )
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 __init__ , be...
> > > p = edge ( 5 , 7 ) > > > p == edge ( 7 , 5 ) True > > > pedge ( 5 , 7 ) class edge : def __new__ ( cls , a , b ) : return frozenset ( { a , b } )
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 having proble...
`` 32 Syndicate street '' - > { `` street name '' : `` Syndicate street '' , `` apartment number '' : `` 32 '' } '' Street 45 No 100 '' - > { `` street name '' : `` Street 45 '' , `` apartment number '' : `` No 100 '' } '' 15 , Tom and Jerry Street '' - > { `` street name '' : `` Tom and Jerry Street '' , `` apartment ...
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 .
ds = pd.Series ( [ ' [ 1 -2 0 1.2 4.34 ] ' , ' [ 3.3 4 0 -1 9.1 ] ' ] ) arr = np.array ( [ [ 1 , -2 , 0 , 1.2 , 4.34 ] , [ 3.3 , 4 , 0 , -1 , 9.1 ] ] ) ds1 = ds.apply ( lambda x : [ float ( number ) for number in x.strip ( ' [ ] ' ) .split ( ' ' ) ] )
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 've gotten...
data = np.arange ( 35 , dtype=np.float32 ) .reshape ( 7 , 5 ) data = pd.concat ( ( pd.DataFrame ( list ( 'abcdefg ' ) , columns= [ 'field1 ' ] ) , pd.DataFrame ( data , columns= [ 'field2 ' , '2014 ' , '2015 ' , '2016 ' , '2017 ' ] ) ) , axis=1 ) data.iloc [ 1:4 , 4 : ] = np.nandata.iloc [ 4 , 3 : ] = np.nanprint ( dat...
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 precisely is l...
pythonPython 2.7.6 ( default , Jan 13 2014 , 14:59:37 ) ... > > > import sys > > > for key in sys.modules.iterkeys ( ) : ... print ( key ) ... ossysabcothers ... > > > abcTraceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > NameError : name 'abc ' is not defined
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 stupid qu...
isValid value1 value2True 50 50True 19 19False 48 40 isValid value1 value2False 50 50False 19 19False 48 40 isValid value1 value2True 50 50False 19 19True 48 40
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 ?
+ -- -- -- -- -- -- -- -- + -- -- -- -+| class | year |+ -- -- -- -- -- -- -- -- + -- -- -- -+| [ ' A ' , ' B ' ] | 2001 || [ ' A ' ] | 2002 || [ ' B ' ] | 2001 || [ ' A ' , ' B ' , ' C ' ] | 2003 || [ ' B ' , ' C ' ] | 2001 || [ ' C ' ] | 2003 |+ -- -- -- -- -- -- -- -- + -- -- -- -+ + -- -- -+ -- -- + -- -- + -- -- +...
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 and disa...
import sysfrom PyQt4 import QtGuiclass Test ( QtGui.QWidget ) : def __init__ ( self ) : super ( ) .__init__ ( ) self.show ( ) app = QtGui.QApplication ( sys.argv ) _ = Test ( ) sys.exit ( app.exec_ ( ) )
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 how to get ...
import plotly.graph_objects as golables = [ ' a ' , ' b ' , ' c ' ] values = [ 30,20,10 ] difference = [ str ( values [ 0 ] - x ) for x in values [ 1 : ] ] fig = go.Figure ( data= go.Bar ( x=lables , y=values , width = [ 0.5,0.5,0.5 ] ) ) fig.add_annotation ( x=lables [ 0 ] , y= values [ 0 ] , xref= '' x '' , yref= '' ...
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 than 80 i...
ip_df : class name marks min_marks min_subjects0 I tom [ 89,85,80,74 ] 80 21 II sam [ 65,72,43,40 ] 85 1 op_df : class name marks min_marks min_subjects flag0 I tom [ 89,85,80,74 ] 80 2 11 II sam [ 65,72,43,40 ] 85 1 0
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 referenc...
class PlotData ( ) : `` '' '' Base Class '' '' '' subclasslist = [ ] @ classmethod def register ( cls ) : super ( ) .subclasslist.append ( cls ) def __new__ ( self , initdata , *args , **kwargs ) : for subclass in subclasslist : try : subclass.__test__ ( initdata ) except AssertionError : continue else : break else : r...
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 multiple outpu...
import remdls_output = `` '' '' kMDItemAuthors = ( margheim ) kMDItemContentCreationDate = 2015-07-10 14:41:01 +0000kMDItemContentModificationDate = 2015-07-10 14:41:01 +0000kMDItemContentType = `` com.adobe.pdf '' kMDItemContentTypeTree = ( `` com.adobe.pdf '' , `` public.data '' , `` public.item '' , `` public.compos...
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 position ( 0 ) ,...
d = { 0 : [ 3 , 5 ] , 1 : [ 5 , 7 ] , 2 : [ 4 , 7 ] , 3 : [ 4 , 3 ] } { 0 : [ 3 , 5 ] , 1 : [ 5 , 7 ] , 2 : [ 7 , 4 ] , 3 : [ 4 , 3 ] } [ 0 , 1 ] [ 1 , 2 ] [ 2 , 3 ] [ 3 , 0 ] { 'foo ' : [ 2 , 9 ] , 'bar ' : [ 3 , 2 ] , 'baz ' : [ 3 , 9 ] } [ 2 , 9 ] , [ 9 , 3 ] , [ 3 , 2 ] l = list ( sorted ( d.values ( ) ) ) for i in...
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 expecting poin...
int print_and_mutate ( char *str ) { str [ 0 ] = ' X ' ; return printf ( `` % s\n '' , str ) ; } from ctypes import *lib = cdll.LoadLibrary ( `` foo.so '' ) s = b '' asdf '' lib.print_and_mutate ( s )
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 .
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 ) ?
from joblib import Parallel , delayed # prediction model - 10s of megabytes on diskLARGE_MODEL = load_model ( 'path/to/model ' ) file_paths = glob ( 'path/to/files/* ' ) def do_thing ( file_path ) : pred = LARGE_MODEL.predict ( load_image ( file_path ) ) return predParallel ( n_jobs=2 ) ( delayed ( do_thing ) ( fp ) fo...
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 number in ...
import pandas as pdfinal_NN = pd.DataFrame ( { `` number '' : [ 123 , 456 , `` Unknown '' , `` Unknown '' , `` Unknown '' , `` Unknown '' , `` Unknown '' , `` Unknown '' , `` Unknown '' , `` Unknown '' ] , `` ID '' : [ `` '' , `` '' , `` '' , `` '' , `` '' , `` '' , `` '' , `` '' , 799 , 813 ] , `` code '' : [ `` '' , ...
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 TypeError ...
def f ( x ) : return { `` x '' : x } def augment ( func ) : def augmented_function ( x ) : return { **func ( x ) , `` metadata '' : `` test '' } return augmented_function async def f ( x ) : return { `` x '' : x } def augment_async ( coro ) : xxxaugment_async ( f ) ( 1 ) # Should return < coroutine object xxx > await a...
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 ' ) .
import numpy as npa = np.array ( [ .4 ] , dtype='float32 ' ) b = np.array ( [ .4 , .6 ] ) print ( a > b ) print ( a > b [ 0 ] , a > b [ 1 ] ) print ( a [ 0 ] > b [ 0 ] , a [ 0 ] > b [ 1 ] ) [ True False ] [ False ] [ False ] True False
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
aiodns==0.3.2aiohttp==1.1.5amqp==1.4.7anyjson==0.3.3astroid==1.3.2asyncio==3.4.3asyncio-redis==0.14.1billiard==3.3.0.20blist==1.3.6boto==2.38.0celery==3.1pexpect==4.0pycryptodomex==3.7.0pycurl==7.19.5.1pyinotify==0.9.6pylint==1.4.0pyminifier==2.1pyOpenSSL==0.15.1pypacker==2.9pyquery==1.2.9pysmi==0.3.2pysnmp==4.4.4PySta...
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 ?
'/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 possible ? S...
list2 = [ x for x in range ( 10 ) ] list1 = [ x for x in range ( 10,20 ) ] for k , list1 in enumerate ( [ list1 , list2 ] ) : for number , entry in enumerate ( list1 ) : print number , entry list2 = [ x for x in range ( 10 ) ] list1 = [ x for x in range ( 10,20 ) ] for k , NEWVAR in enumerate ( [ list1 , list2 ] ) : fo...
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 from . Th...
df1 id speed accelaration jerk mode0 1 1.94 -1.01 1.05 foot1 1 0.93 0.04 -0.17 foot2 3 0.50 -0.16 0.05 bike3 3 0.57 0.05 0.19 bike4 5 3.25 -0.13 -0.09 bus5 5 0.50 -0.25 0.25 bus6 5 0.25 0.10 0.25 busdf2 id speed accelaration jerk mode0 17 1.5 0.00 0.00 foot1 17 1.5 0.00 -0.30 foot2 17 1.5 -0.30 0.06 foot3 15 4.55 0.01 ...
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 with mor...
height weight shoe_size age0 175 70 40 301 175 75 39 412 175 69 40 333 176 71 40 354 178 81 41 275 169 73 38 496 170 65 39 30 ( 'weight ' : 2.0 ) == > ( 'height ' : 1.0 ) height weight shoe_size age2 175 69 40 330 175 70 40 303 176 71 40 35 ( 'height ' : 1.0 , 'age ' : 6.0 ) == > ( 'weight ' : 4.0 ) height weight shoe_...
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 [ [ ] ] should...
x = [ [ ] ] x [ 0 ] .extend ( x ) y = [ ] # equivalent to x [ 0 ] x = [ [ ] ] y.extend ( x )
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 obtained is :...
L = [ [ 1,2,3 ] , [ 4,5,6 ] , [ 3,4,6 ] ] [ [ 2,4,6 ] , [ 8,10,12 ] , [ 6,8,12 ] ] for x in range ( len ( L ) ) : for y in range ( len ( L [ x ] ) ) : L [ x ] [ y ] = L [ x ] [ y ] + L [ x ] [ y ] print L for x in L : a = L.index ( x ) for y in L [ a ] : b = L [ a ] .index ( y ) L [ a ] [ b ] = L [ a ] [ b ] + L [ a ] ...
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 ?
def cart ( *iterables ) : out = ( ( e , ) for e in iterables [ 0 ] ) for iterable in iterables [ 1 : ] : out = ( e1 + ( e2 , ) for e1 in out for e2 in iterable ) return out print ( list ( cart ( [ 1 , 2 , 3 ] , 'ab ' , [ 4 , 5 ] ) ) ) [ ( 1 , 4 , 4 ) , ( 1 , 4 , 5 ) , ( 1 , 5 , 4 ) , ( 1 , 5 , 5 ) , ( 2 , 4 , 4 ) , ( 2...
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_ _ _ _ pattern is th...
word_1 word_2 id number nunca nunca RG 0.293030first_word second_word VM223FDS 0.902333error errpr RG 0.345355667nunca nunca RG 0.1489098ninguna ninguno DI0S3DF 0.345344third fourth VM34SDF 0.7865489 [ ( nunca , RG ) , ( second_word , VM223FDS ) ] nunca nunca RG 0.293030prendas prenda NCFP000 0.95625success success VM2...
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 min value...
pd.DataFrame ( { ' A ' : [ 'C1 ' , 'C2 ' , 'C3 ' , 'C4 ' , 'C5 ' , 'C6 ' , 'C7 ' , 'C8 ' , 'C9 ' , 'C10 ' ] , ... : ' B ' : [ ' A ' , ' A ' , ' A ' , ' B ' , ' B ' , ' B ' , ' B ' , ' C ' , ' C ' , ' C ' ] , ... : ' W ' : [ 0.5 , 0.2 , 0.3 , 0.2 , 0.1 , 0.4 , 0.3 , 0.4 , 0.5 , 0.1 ] , ... : ' V ' : [ 9 , 1 , 7 , 4 , 3 ...
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 ( change every ...
def first ( ) : # crop img_crop = mpimg.imread ( 'Crop.jpg ' ) # img_crop = numpy.load ( 'bur.npy ' ) x = numpy.arange ( 10 ) y = numpy.arange ( 20 ) X , Y = numpy.meshgrid ( x , y ) img_crop_re = cv2.resize ( img_crop , dsize= ( 200,200 ) , interpolation=cv2.INTER_CUBIC ) img_crop_ro = cv2.rotate ( img_crop_re , cv2.R...
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 that , othe...
class OldStyle : pass class NewStyle ( object ) : pass class NewStyle2 : __metaclass__ = type
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 understand w...
def funk ( ) : return ( `` Some text '' ) msg= '' '' if ( msg=funk ( ) ) == `` Some resut '' : print ( `` Result 1 '' ) # include < stdio.h > char funk ( ) { return ' a ' ; } int main ( ) { char a ; if ( a=funk ( ) == ' a ' ) printf ( `` Hello , World ! \n '' ) ; return 0 ; }
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 an empty l...
Slot Time Last Next1 9:30 9:372 9:35 9:32 9:403 9:40 9:37 9:524 9:45 9:41 9:475 9:50 9:47 10:00 df [ 'min ' ] = [ NaN,1,2,3,4 ] anddf [ 'max ' ] = [ 2,2,5,4,5 ] for index , row in df.iterrows ( ) : row [ 'min ' ] = df [ df [ 'Time ' ] < row [ 'Last ' ] ] [ 'Slot ' ]
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
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 ?
df = index data1 data20 20 1201 30 4562 40 34 my_list = [ 20,120,30,456,40,34 ] list1 = df [ 'data1 ' ] .tolist ( ) list2 = df [ 'data2 ' ] .tolist ( ) my_list = list1+list2
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 :
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 ) ) super ( Example , self ) .__init__ ( ) ... self.btnConnect.clicked.connect ( self.connectserver ) self.btnConnect.clicked.connect ( self....
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 class . Wha...
class X ( object ) : def __len__ ( self ) : return 1 < < 31try : len ( X ( ) ) except OverflowError : # 32-bit MAXSIZE = int ( ( 1 < < 31 ) - 1 ) else : # 64-bit MAXSIZE = int ( ( 1 < < 63 ) - 1 ) del X try : 1 < < 31except OverflowError : # 32-bit MAXSIZE = int ( ( 1 < < 31 ) - 1 ) else : # 64-bit MAXSIZE = int ( ( 1 ...
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 matches : A...
word1Word2w0rd3word4word5word6word7word8word9w0rd10word11word12Word13w0rd14word15word16word17 ( word1 ) or ( word1/Word2/w0rd3 ) \ ( ( \w+ ) \/ ( \w+ ) \/ ( \w+ ) \ ) [ ^ ( ] *\ ( ( \w+ ) \/ ( \w+ ) \ ) [ ^ ( ] *\ ( ( \w+ ) \ )
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 'm getting...
for row in all_rows : base_col = base_col.combine_first ( row )
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 of the *g...
class PolyExt ( Poly ) : def __init__ ( self , expression , symb1 , symb2 ) : self.symb1 = symb1 self.symb2 = symb2 super ( PolyExt , self ) .__init__ ( expression ) x = symbols ( ' x ' ) y = symbols ( ' y ' ) PolyExt ( x+y , [ y ] , [ x ] ) class Poly ( Expr ) : `` '' '' Generic class for representing polynomial expre...
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 can be a ...
ip = { `` 1 '' : [ ' a ' , ' b ' ] , `` 2 '' : [ ' a ' , ' c ' ] , `` 3 '' : [ ' a ' , ' b ' , ' c ' , 'd ' ] , `` 4 '' : [ ' a ' , ' b ' , 'd ' , ' e ' ] } op = { `` a '' :4 , '' b '' :3 , '' c '' :2 , '' d '' :2 , '' e '' :1 } op = [ ( ' a ' , 4 ) , ( ' b ' , 3 ) , ( ' c ' , 2 ) , ( 'd ' , 2 ) , ( ' e ' , 1 ) ] op = ...
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
a , b = 0 , 1while b < 10 : print ( b ) a , b = b , a+b a , b = 0 , 1while b < 10 : print ( b ) a = b 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 take an ar...
def my_decorator ( func ) : def inner ( *args , **kwargs ) : print ( 'Before function runs ' ) func ( *args , **kwargs ) print ( 'After function ran ' ) return inner @ my_decoratordef foo ( thing_to_print ) : print ( thing_to_print ) foo ( 'Hello ' ) # Returns : # Before function runs # Hello # After function ran foo =...
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 :
df = pd.DataFrame ( { `` u1 '' : [ 1,2 , -3,4,5 ] , `` u2 '' : [ 8 , -4,5,6,7 ] , `` u3 '' : [ np.NaN , np.NaN , np.NaN , np.NaN , np.NaN ] } , index= [ `` q1 '' , '' q2 '' , '' q3 '' , '' q4 '' , '' q5 '' ] ) u1 u2 u3q5 q1 NaNq4 q5 NaNq2 q4 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
re.split ( '\\s* ( [ a-zA-Z\\d ] [ ) . ] |• ) \\s* ( ? = [ A-Z ] ) ' , text )
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 .
s = 'abc ' [ ( c1 , c2 ) for j , c2 in enumerate ( s ) for i , c1 in enumerate ( s ) ] [ ( ' a ' , ' a ' ) , ( ' b ' , ' a ' ) , ( ' c ' , ' a ' ) , ( ' a ' , ' b ' ) , ( ' b ' , ' b ' ) , ( ' c ' , ' b ' ) , ( ' a ' , ' c ' ) , ( ' b ' , ' c ' ) , ( ' c ' , ' c ' ) ] it1 , it2 = enumerate ( s ) , enumerate ( s ) [ ( c...
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 case . Wha...
x = array ( 'd ' , [ 0 ] * 1000000 ) x = array ( 'd ' , [ 0 ] ) * 1000000
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 question is...
from mailbox import MailboxMailbox.get = 'dummy ' from datetime import datetimedatetime.now = 'dummy ' TypeError : ca n't set attributes of built-in/extension type 'datetime.datetime '
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 variants ...
df = pd.DataFrame ( data= { ' A ' : range ( 1,9 ) , ' B ' : range ( 1,9 ) , ' C ' : range ( 1,9 ) } , index=pd.MultiIndex.from_tuples ( [ ( 'seqA ' , 'wt ' ) , ( 'seqA ' , 'm1 ' ) , ( 'seqA ' , 'm2 ' ) , ( 'seqB ' , 'wt ' ) , ( 'seqB ' , 'm1 ' ) , ( 'seqB ' , 'm2 ' ) , ( 'seqB ' , 'm3 ' ) , ( 'seqC ' , 'wt ' ) ] ) ) df...
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 :
df = pd.DataFrame ( { `` a '' : [ 1 , 2 , 3 ] , `` b '' : [ 4 , 5 , 6 ] , `` c '' : [ 7 , 8 , 9 ] , `` d '' : [ 10 , 11 , 12 ] , `` e '' : [ 13 , 14 , 15 ] } ) df.iloc [ : , 1:4 ] df.SOME_FUNCTION_OR_A_SPECIFIC_SYNTAX ( `` b '' , `` d '' )
Python Pandas : Selection of Columns by Column Names
Python
I got this : So in this case Why is
# 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 thing is p...
class Particle : def __init__ ( self , pos , angle ) : self.pos = pos self.angle = angle self.color = choice ( [ ( 217 , 103 , 51 ) , ( 238 , 95 , 30 ) ] ) self.radius = uniform ( 2 , 7 ) self.pull = 0 self.start = time.time ( ) def adjust ( self ) : self.radius -= 0.03 def draw ( self ) : if self.radius > 0 : pygame.d...
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
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 ) ) : for j in range ( len ( arr [ x ] ) ) : example = example + str ( arr [ x ] [ j ] ) print ( example )
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 that __in...
> > > import numpy as np > > > import sys > > > np.broadcast.__module__'numpy ' > > > sys.modules [ np.broadcast.__module__ ] < module 'numpy ' from '/Users/brad/ ... /site-packages/numpy/__init__.py ' >
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 .
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 like this i...
class MyClass : def __init__ ( self ) : passx = MyClassx.new = 5print ( x.new ) # prints 5 x.first.second = 1 # this will raise x.first = MyClass ( ) x.first.second = 1print ( x.first.second )
How can I recursively create class properties in Python ?
Python
Consider this statement : However : It is incredible . What 's the reason and the interpretation ?
> 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
a = np.array ( [ 2,4,6 ] ) result = [ ] for a1 , a2 in zip ( a*2 , a*2+1 ) : result = result + [ a1 , a2 ] print ( result ) # Output : [ 4 , 5 , 8 , 9 , 12 , 13 ]
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 and .tolis...
# split string and sort into columns df1 = pd.DataFrame ( eventsDf.comment.str.split ( ) .tolist ( ) , columns= '' 0 0 0 0 0 0 dutyCycle 0 Gas 0 Pressure 0 `` .split ( ) ) # join dataFrameseventsDf = pd.concat ( [ eventsDf , df1 ] , axis=1 ) # drop columns not neededeventsDf.drop ( [ 'comment ' , ' 0 ' , ] , axis=1 , i...
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 ?
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 ?
import requestsfrom bs4 import BeautifulSoup URL = 'https : //www.spotrac.com/nfl/rankings/'reqs = requests.get ( URL ) soup = BeautifulSoup ( reqs.text , 'lxml ' ) print ( `` List of all the h1 , h2 , h3 : '' ) for my_tag in soup.find_all ( class_= '' team-name '' ) : print ( my_tag.text ) for my_tag in soup.find_all ...
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
finaldata [ 'keyword ' ] = finaldata [ 'keyword ' ] .str.replace ( `` Washington Times '' , `` '' ) finaldata [ 'keyword ' ] = finaldata [ 'keyword ' ] .str.replace ( `` Washington Post '' , `` '' ) finaldata [ 'keyword ' ] = finaldata [ 'keyword ' ] .str.replace ( `` Mail The Globe '' , `` '' )
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 !
df = pd.DataFrame ( { 'Col1 ' : [ 'Table_A112 ' , 'Table_A_112 ' ] } ) Table_A112Table_A_ import pandas as pdimport difflibfrom tabulate import tabulateimport stringdf = pd.DataFrame ( { 'Col1 ' : [ 'Table_A112 ' , 'Table_A_112 ' ] } ) print ( tabulate ( df , headers='keys ' , tablefmt='psql ' ) ) df [ 'Col2 ' ] = df [...
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 the previo...
df = pd.DataFrame ( { 'ID ' : [ 'James ' , 'James ' , 'James ' , 'Max ' , 'Max ' , 'Max ' , 'Max ' , 'Park ' , 'Tom ' , 'Tom ' , 'Tom ' , 'Tom ' , 'Wong ' ] , 'From_num ' : [ 78 , 420 , 'Started ' , 298 , 36 , 298 , 'Started ' , 'Started ' , 60 , 520 , 99 , 'Started ' , 'Started ' ] , 'To_num ' : [ 96 , 78 , 420 , 36 ,...
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 ( ) ?
[ 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 importlib mag...
# A.pyimport B # B.pyimport Cprint ( 'hello from B ' ) # C.pypass # B.sothis is a fake binary # A.pyimport impB = imp.load_source ( ' B ' , ' B.py ' ) # C.sothis is a fake binary
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 : https : ...
if False : passelif basecmd in ( 'erase-n ' , 'remove-n ' ) : rms = self.remove ( name=arg ) ...
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 slicing , s...
temp = [ ( 1 , 0 , 1 , 0 , 2 ) , ( 1 , 0 , 1 , 0 , 5 ) , ( 1 , 0 , 2 , 0 , 2 ) , ( 1 , 0 , 2 , 0 , 5 ) ] first_elements = temp [ : ,0 ]
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 two other...
# ! /usr/bin/env pythonclass _MyClass ( object ) : def __init__ ( self ) : self.val = `` Default '' my_instance = _MyClass ( ) # ! /usr/bin/env pythonfrom my_lib import my_instancemy_instance.val = `` File A was here ! `` import file_bfile_b.check_val ( ) # ! /usr/bin/env pythonfrom my_lib import my_instancedef check_v...
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 ' . What 's ...
data = [ ( 1.0 , 2 ) , ( 3.0 , 4 ) ] np.array ( data , dtype= [ ( ' x ' , str ) , ( ' y ' , int ) ] ) array ( [ ( `` , 2 ) , ( `` , 4 ) ] , dtype= [ ( ' x ' , 'S ' ) , ( ' y ' , ' < i8 ' ) ] ) str ( 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 have to en...
python -m collectiondbf [ myargumentshere.. ] import jsonif user_inputed_keys : with open ( 'config.json ' , ' w ' ) as f : json.dump ( { 'api_key ' : api_key } , f )
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 = first ...
x = np.array ( [ [ 1 , 2 , 1 ] , [ 3 , 2 ,1 ] , [ 1 , 2 , 2 ] ] ) w = np.array ( [ 0.3 , 0.4 , 0.3 ] )
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 .
# Module.pyclass TestClass : name = `` default '' nameDict = { 'name ' : '' standard '' } def __init__ ( self , name ) : self.name = name self.nameDict [ 'name ' ] = name Module.TestClass ( `` newName '' ) # Inside another functionprint ( Module.TestClass.name ) print ( Module.TestClass.nameDict [ 'name ' ] ) default #...
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 n is the...
def plot_psi ( n , l , start= ( 0.001*bohr ) , stop= ( 20*bohr ) , step= ( 0.005*bohr ) ) : def plot_psi ( n , l , start= ( 0.001*bohr ) , stop= ( ( 30*n-10 ) *bohr ) , step= ( 0.005*bohr ) ) :
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 '' ) = [ 9+0...
df = pd.DataFrame ( np.random.randint ( 0,10 , size= ( 7,3 ) ) , columns= [ `` a '' , '' b '' , '' c '' ] ) df [ `` d1 '' ] = [ `` Apple '' , '' Mango '' , '' Apple '' , '' Mango '' , '' Mango '' , '' Mango '' , '' Apple '' ] df [ `` d2 '' ] = [ `` Orange '' , '' lemon '' , '' lemon '' , '' Orange '' , '' lemon '' , ''...
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 how I can ...
def merge ( list1 , list2 ) : count1 = count2 = 0 final = [ ] while count1 < len ( list1 ) and count2 < len ( list1 ) : if list1 [ count1 ] < = list2 [ count2 ] : final.append ( list1 [ count1 ] ) count1 += 1 else : final.append ( list2 [ count2 ] ) count2 += 1 if count1 == len ( list1 ) : for i in range ( count2 , len...
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 , height , or le...
def create_box ( **kwargs ) : box = Box ( ) set_size ( box , **kwargs ) set_appearance ( box , **kwargs ) def set_size ( box , width=1 , height=1 , length=1 ) : ... def set_appearance ( box , material='cardboard ' , color='brown ' ) : ... def create_box ( width=1 , height=1 , length=1 , material='cardboard ' , color='b...
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 , they h...
class MyClass : def something ( ) : passa = MyClass ( ) b = MyClass ( ) id ( a.something ) , id ( b.something ) # ( 4487791304 , 4487791304 ) id ( a.something ) is id ( b.something ) # [ '__class__ ' , '__delattr__ ' , '__dict__ ' , '__dir__ ' , '__doc__ ' , '__eq__ ' , '__format__ ' , '__ge__ ' , '__getattribute__ ' ,...
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 :
word77 text text bla66 word78 text bla67text bla68 word79 text bla69 word80 textbla77 word81 text bla78 word92 text bla79 word99 word1 text text bla1 word2 text bla2text bla3 word3 text bla4 word4 textbla5 word5 text bla6 word6 text bla7 word7 import redef replace ( m ) : global i ; i+=1 ; return str ( i ) ; fp = open ...
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 point of...
2+2 2+ 2+++2
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 trying to `` ...
> > > def gen ( ) : ... for i in range ( 5 ) : ... yield i ... > > > count=gen ( ) > > > for i in count : ... print count.next ( ) ... 13Traceback ( most recent call last ) : File `` < stdin > '' , line 2 , in < module > StopIteration > > >
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 ' ) ) , I ...
data= [ [ 0,1,5 ] , [ 0,1,6 ] , [ 0,0,8 ] , [ 0,0,10 ] , [ 0,1,12 ] , [ 0,0,14 ] , [ 0,1,16 ] , [ 0,1,18 ] , [ 1,0,2 ] , [ 1,1,0 ] , [ 1,0,1 ] , [ 1,0,2 ] ] df = pd.DataFrame ( data , columns= [ 'KEY ' , 'COND ' , 'VAL ' ] ) KEY COND VAL RES1 RES20 0 1 5 5 51 0 1 6 6 62 0 0 8 63 0 0 10 64 0 1 12 7 75 0 0 14 76 0 1 16 8...
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 handles ? Per...
def g ( filename ) : with open ( filename ) as handle : for line in handle : yield some_trasformation_on ( line ) res = g ( ) print ( next ( res ) )
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 .
id name0 4 Bert1 5 Ernie2 6 Jeff3 7 Bob4 8 Puppy5 9 Socks6 12 Cyoot user_email likes0 matt @ google.com [ 4 , 5 , 6 , 7 , 8 , 9 , 12 ] 1 gabe @ google.com [ 4 , 8 , 9 , 6 , 5 , 12 ]
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 gcloud : g...
from flask import ( Flask ) from flask_cors import CORSapp = Flask ( __name__ ) cors = CORS ( app ) @ app.route ( '/ping ' , methods= [ 'GET ' ] ) def ping ( ) : return 'It works ! ' , 200def create_app ( ) : return appif __name__ == '__main__ ' : app.run ( ) FROM python:3.7-slimCOPY . ./home/gcloud-testWORKDIR /home/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 do the f...
long_descriptive_variable_name = some_function ( long_descriptive_variable_name ) some_function ! ( long_descriptive_variable_name ) long_variable_name = long_variable_name.method ( arg1 , arg2 )
Mutating / in-place function invokation or adaptation in Python