lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | This following is a snippet of Python code I found that solves a mathematical problem . What exactly is it doing ? I was n't too sure what to Google for.Is this a special Python syntax ? | x , y = x + 3 * y , 4 * x + 1 * y | What is this piece of Python code doing ? |
Python | I know in languages such as C , C++ , Java and C # , ( C # example ) the else if statement is syntactic sugar , in that it 's really just a one else statement followed by an if statement . is equal to However , in python , there is a special elif statement . I 've been wondering if this is just shorthand for developers... | else if ( conition ( s ) ) { ... else { if ( condition ( s ) ) { ... } | Is the python `` elif '' compiled differently from else : if ? |
Python | Consider the next example : I 'm using cp1251 encoding within the idle , but it seems like the interpreter actually uses latin1 to create unicode string : Why so ? Is there spec for such behavior ? CPython , 2.7.EditThe code I was actually looking for isSeems like when encoding unicode with latin1 codec , all unicode p... | > > > s = u '' баба '' > > > su'\xe1\xe0\xe1\xe0 ' > > > print sáàáà > > > print s.encode ( 'latin1 ' ) баба > > > u'\xe1\xe0\xe1\xe0 ' == u'\u00e1\u00e0\u00e1\u00e0'True | Encoding used for u '' '' literals |
Python | I have a strange behaviour with pybind11 when I want to use C++ polymorphism in Python . Here is a simple example of my problem : The output of this script is [ MyBase , MyDerived ] MyBase MyBasebut the expected output is [ MyBase , MyDerived ] MyBase MyDerivedbecause mylist return a std : :vector which contains an ins... | import polymorphism as plma = plm.mylist ( ) print ( a ) a [ 0 ] .print ( ) a [ 1 ] .print ( ) /* polymorphism.hpp */ # ifndef POLYMORPHISM_HPP # define POLYMORPHISM_HPP # include < vector > class MyBase { public : virtual void print ( ) const ; } ; class MyDerived : public MyBase { public : virtual void print ( ) cons... | Polymorphism and pybind11 |
Python | I 'm having issues with reverting a Django ( 1.8.7 ) migration that contains the renaming of a table . Even though it seems to be able to rename it in Postgres , it then tries to add a constraint using the old table name.Here 's the traceback : If you take a look at the SQL it generates , You can see that there 's a re... | cursor.execute ( sql , params ) File `` /Users/myworkspace/projects/xxx/venv/lib/python3.5/site-packages/django/db/backends/utils.py '' , line 79 , in execute return super ( CursorDebugWrapper , self ) .execute ( sql , params ) File `` /Users/myworkspace/projects/xxx/venv/lib/python3.5/site-packages/django/db/backends/... | Error when reverting an auto-generated migration for renaming a table in Django |
Python | Converting a loop into a comprehension is simple enough : toBut I 'm not sure how to proceed when the loop involves assigning a value to a reference.And the comprehension ends up looking like this : This calculates word.split ( ' l ' ) multiple times whereas the loop only calculates it once and saves a reference . I 'v... | mylist = [ ] for word in [ 'Hello ' , 'world ' ] : mylist.append ( word.split ( ' l ' ) [ 0 ] ) mylist = [ word.split ( ' l ' ) [ 0 ] for word in [ 'Hello ' , 'world ' ] ] mylist = [ ] for word in [ 'Hello ' , 'world ' ] : split_word = word.split ( ' l ' ) mylist.append ( split_word [ 0 ] +split_word [ 1 ] ) mylist = [... | Converting a loop with an assignment into a comprehension |
Python | I 'm trying to calculate the weighted topological overlap for an adjacency matrix but I can not figure out how to do it correctly using numpy . The R function that does the correct implementation is from WGCNA ( https : //www.rdocumentation.org/packages/WGCNA/versions/1.67/topics/TOMsimilarity ) . The formula for compu... | > library ( WGCNA , quiet=TRUE ) > df_adj = read.csv ( `` https : //pastebin.com/raw/sbAZQsE6 '' , row.names=1 , header=TRUE , check.names=FALSE , sep= '' \t '' ) > df_tom = TOMsimilarity ( as.matrix ( df_adj ) , TOMType= '' unsigned '' , TOMDenom= '' min '' ) # ..connectivity.. # ..matrix multiplication ( system BLAS ... | How to compute the Topological Overlap Measure [ TOM ] for a weighted adjacency matrix in Python ? |
Python | PIP always downloads and installs a package when a specific SVN revision is specified ( slowing the syncing process considerably ) . Is there a way around this ? Normally pip detects that the package is already installed in the environment and prompts to use -- upgrade.My pip_requirements file has the following line : ... | svn+http : //code.djangoproject.com/svn/django/trunk/ @ 16406 # egg=Django1.4A | PIP always reinstalls package when using specific SVN revision |
Python | While I was messing around with Python , Although I understand that 'conjugate ' , 'imag ' , and 'real ' are there for the sake of compatibility with complex type , I ca n't understand why 'numerator ' and 'denominator ' exists for int only , and does n't for a float . Any explanation for that ? | > > > [ attr for attr in dir ( 1 ) if not attr.startswith ( ' _ ' ) ] [ 'bit_length ' , 'conjugate ' , 'denominator ' , 'imag ' , 'numerator ' , 'real ' ] > > > [ attr for attr in dir ( 1.1 ) if not attr.startswith ( ' _ ' ) ] [ 'as_integer_ratio ' , 'conjugate ' , 'fromhex ' , 'hex ' , 'imag ' , 'is_integer ' , 'real ... | Why float objects in Python does n't have denominator attribute , while int does ? |
Python | I have a c++ vector with std : :pair < unsigned long , unsigned long > objects . I am trying to generate permutations of the objects of the vector using std : :next_permutation ( ) . However , I want the permutations to be of a given size , you know , similar to the permutations function in python where the size of the... | import itertoolslist = [ 1,2,3,4,5,6,7 ] for permutation in itertools.permutations ( list , 3 ) : print ( permutation ) ( 1 , 2 , 3 ) ( 1 , 2 , 4 ) ( 1 , 2 , 5 ) ( 1 , 2 , 6 ) ( 1 , 2 , 7 ) ( 1 , 3 , 2 ) ( 1 , 3 , 4 ) .. ( 7 , 5 , 4 ) ( 7 , 5 , 6 ) ( 7 , 6 , 1 ) ( 7 , 6 , 2 ) ( 7 , 6 , 3 ) ( 7 , 6 , 4 ) ( 7 , 6 , 5 ) | How to create a permutation in c++ using STL for number of places lower than the total length |
Python | I 've got an iterator with some objects in it and I wanted to create a collection of uniqueUsers in which I only list every user once . So playing around a bit I tried it with both a list and a dict : So I tested it by converting the dict to a list when doing the if statement , and that works as I would expect it to : ... | > > > for m in ms : print m.to_user # let 's first look what 's inside ms ... Pete KramerPete KramerPete Kramer > > > > > > uniqueUsers = [ ] # Create an empty list > > > for m in ms : ... if m.to_user not in uniqueUsers : ... uniqueUsers.append ( m.to_user ) ... > > > uniqueUsers [ Pete Kramer ] # This is what I would... | ` object in list ` behaves different from ` object in dict ` ? |
Python | I have been playing around with SQLAlchemy and found out that I can not track reliably what is being changed within database.I have created an example that explains what my concern is : In short - there are two objects : ParentChild - linked to ParentEach time I add new instance of Child and link it with instance of Pa... | import reimport datetimefrom sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import ( declarative_base , declared_attr , ) from sqlalchemy import ( create_engine , event , Column , Boolean , Integer , String , Unicode , DateTime , Index , ForeignKey , CheckConstraint , ) from sqlalchemy.orm import ( scop... | Make parent object not appearing within session.dirty of before_flush event listener |
Python | I wrote a line of code using lambda to close a list of file objects in python2.6 : It works , but does n't in python3.1 . Why ? Here is my test code : | map ( lambda f : f.close ( ) , files ) import sysfiles = [ sys.stdin , sys.stderr ] for f in files : print ( f.closed ) # False in 2.6 & 3.1map ( lambda o : o.close ( ) , files ) for f in files : print ( f.closed ) # True in 2.6 but False in 3.1for f in files : f.close ( ) for f in files : print ( f.closed ) # True in ... | Could n't close file in functional way in python3.1 ? |
Python | Python2.7 output format not getting as expected if body of email read from a file . user_info.txt is a file generated by another job which contains all the details of users . The output format of user_info.txt is nice . Where as sending that file as an email , output format changes completely . does am I doing somethin... | # ! /usr/bin/env pythonimport smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextmsg = MIMEMultipart ( 'alternative ' ) msg [ 'Subject ' ] = `` User Info '' '' '' '' Create the body of the message '' '' '' open_file = open ( '/tmp/user_info.txt ' ) user_info = MIMEText ( open_file.... | stdout format changing when sending a file using smtplib - python2.7 |
Python | how should I define a function , where , which can tell where it was executed , with no arguments passed in ? all files in ~/app/a.py : b.py : c.py : | def where ( ) : return 'the file name where the function was executed ' from a import whereif __name__ == '__main__ ' : print where ( ) # I want where ( ) to return '~/app/b.py ' like __file__ in b.py from a import whereif __name__ == '__main__ ' : print where ( ) # I want where ( ) to return '~/app/c.py ' like __file_... | Determine where a function was executed ? |
Python | I have a dataset with an id column , date column and value . I would like to count the consecutive appearances/duplicate values of id for a continuous date range.My question is very much like Count consecutive duplicate values by group but in Python.Moreover , the question is different from How to find duplicates in pa... | ID tDate value79 2019-06-21 00:00:00 39779 2019-07-13 00:00:00 40479 2019-07-18 00:00:00 40579 2019-07-19 00:00:00 40679 2019-08-02 00:00:00 41079 2019-08-09 00:00:00 413 ID tDate val consec_count79 2019-06-21 00:00:00 397 079 2019-07-13 00:00:00 404 079 2019-07-18 00:00:00 405 179 2019-07-19 00:00:00 406 279 2019-08-0... | Counting Consecutive Duplicates For By Group |
Python | Just soliciting opinion on whether the following is reasonable or if there is a better approach . Basically I want a decorator that will apply to a function or a class that implements __call__.You could just have a regular decorator and decorate the __call__ explicitly but then the decorator is tucked inside the class ... | import typesfrom functools import wrapsclass dec : `` '' '' Decorates either a class that implements __call__ or a function directly. `` '' '' def __init__ ( self , foo ) : self._foo = foo def __call__ ( self , target ) : wraps_class = isinstance ( target , types.ClassType ) if wraps_class : fun = target.__call__ else ... | python decorator for class OR function |
Python | Following is the __init__ method of the Local class from the werkzeug library : I do n't understand two things about this code : Why did they writeinstead of simplyWhy did they even use __setattr__ if the could simply write | def __init__ ( self ) : object.__setattr__ ( self , '__storage__ ' , { } ) object.__setattr__ ( self , '__ident_func__ ' , get_ident ) object.__setattr__ ( self , '__storage__ ' , { } ) ` setattr ( self , '__storage__ ' , { } ) ` self.__storage__ = { } | ` object.__setattr__ ( self , ... , ... ) ` instead of ` setattr ( self , ... , ... ) ` ? |
Python | I though this question would solve my problem , and I followed the Simple HTTP Server example but I 'm getting different issues that I ca n't find a solution for.I want to generate an Excel file in my server and return it to the user with an Http response . I 'm using xlsxwriter to build the file and a pyramid framwork... | output = StringIO ( ) workbook = xlsxwriter.Workbook ( output ) worksheet = workbook.add_worksheet ( ) # add the dataworkbook.close ( ) excelcontent = output.getvalue ( ) response = Response ( content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet ' , body=excelcontent ) response.headers.add ( ... | Decoding problems when returning xlsxwriter response with pyramid |
Python | I 'm wondering how to match the labels produced by a SVN classifier with the ones on my dataset . ANd then I realized that the problem starts at the begining : when I load the dataset I got a dataset which in my case has the following properties : But I , m wondering if the order og the target_names is different across... | .data = the news text.target_names = label used in the dataset e.g . [ `` positive '' , `` negative '' ] .target = A matrix with a number for each news with a label . | Labels of datasets imported with sklearn.datasets.load_files |
Python | Trying to convert super ( B , self ) .method ( ) into a simple nice bubble ( ) call.Did it , see below ! Is it possible to get reference to class B in this example ? Basically , C is child of B , B is child of A . Then we create c of type C. Then the call to c.test ( ) actually calls B.test ( ) ( via inheritance ) , wh... | class A ( object ) : passclass B ( A ) : def test ( self ) : test2 ( ) class C ( B ) : passimport inspectdef test2 ( ) : frame = inspect.currentframe ( ) .f_back cls = frame . [ ? something here ? ] # cls here should == B ( class ) c = C ( ) c.test ( ) | super ( ) in Python 2.x without args |
Python | Original problem descriptionThe problem arises when I implement some machine learning algorithm with numpy . I want some new class ludmo which works the same as numpy.ndarray , but with a few more properties . For example , with a new property ludmo.foo . I 've tried several methods below , but none is satisfactory.1 .... | import numpy as npclass ludmo ( object ) : def __init__ ( self ) self.foo = None self.data = np.array ( [ ] ) import numpy as npclass ludmo ( np.ndarray ) : def __init__ ( self , shape , dtype=float , buffer=None , offset=0 , strides=None , order=None ) super ( ) .__init__ ( shape , dtype , buffer , offset , strides , ... | Python : How to extend a huge class with minimum lines of code ? |
Python | I 'm thinking to do some bytecode manipulation ( think genetic programming ) in Python.I came across a test case in crashers test section of Python source tree that states : Broken bytecode objects can easily crash the interpreter . This is not going to be fixed.Thus the question , how to validate given tweaked byte co... | cc = ( lambda fc= ( lambda n : [ c for c in ( ) .__class__.__bases__ [ 0 ] .__subclasses__ ( ) if c.__name__ == n ] [ 0 ] ) : fc ( `` function '' ) ( fc ( `` code '' ) ( 0 , 0 , 0 , 0 , `` KABOOM '' , ( ) , ( ) , ( ) , `` '' , `` '' , 0 , `` '' ) , { } ) ( ) ) | How to validate Python bytecode ? |
Python | I have an image array that has an X times Y shape of 2048x2088 . The x-axis has two 20 pixel regions , one at the start and one at the end , which are used to calibrate the main image area . To access these regions I can slice the array like so : My question is how to define these areas in a configuration file in order... | prescan_area = img [ : , :20 ] data_area = img [ : , 20:2068 ] overscan_area = img [ : , 2068 : ] prescan_area_def = `` [ : , :20 ] '' image_area_def = `` [ : , 20:2068 ] '' overscan_area_def = `` [ : , 2068 : ] '' | Using a string to define Numpy array slice |
Python | I am currently working on a jupyter notebook in kaggle . After performing the desired transformations on my numpy array , I pickled it so that it can be stored on disk . The reason I did that is so that I can free up the memory being consumed by the large array . The memory consumed after pickling the array was about 8... | import sysdef sizeof_fmt ( num , suffix= ' B ' ) : `` ' by Fred Cirera , https : //stackoverflow.com/a/1094933/1870254 , modified '' ' for unit in [ `` , 'Ki ' , 'Mi ' , 'Gi ' , 'Ti ' , 'Pi ' , 'Ei ' , 'Zi ' ] : if abs ( num ) < 1024.0 : return `` % 3.1f % s % s '' % ( num , unit , suffix ) num /= 1024.0 return `` % .1... | Jupyter Notebook Memory Management |
Python | I ran into a very surprising relative import behavior today ( unfortantely after nearly 4 hours of pulling my hair out ) .I have always been under the impression that if you have `` Class A '' inside of a module name `` module_a.py '' within a package named `` package '' that you could equivalently use either : oras lo... | from package.module_a import ClassA from module_a import ClassA class ClassA ( object ) : passdef check_from_module_a ( obj ) : print 'from module_a ' print ' -- -- -- -- -- -- - ' print 'class is : ' , ClassA print 'object is ' , type ( obj ) print 'is obj a ClassA : ' , isinstance ( obj , ClassA ) from package.module... | Unexpected relative import behavior in Python |
Python | I have a list my_list ( the list contains utf8 strings ) : For some reason , a sorted list ( my_sorted_list = sorted ( my_list ) ) uses more memory : Why is sorted returning a list that takes more space in memory than the initial unsorted list ? | > > > len ( my_list ) 8777 > > > getsizeof ( my_list ) # < -- note the size77848 > > > len ( my_sorted_list ) 8777 > > > getsizeof ( my_sorted_list ) # < -- note the size79104 | Why is a sorted list bigger than an unsorted list |
Python | I 'm currently developing some things in Python and I have a question about variables scope.This is the code : If I remove the first line ( a = None ) the code still works as before . However in this case I 'd be declaring the variable inside an `` if '' block , and regarding other languages like Java , that variable w... | a = Noneanything = Falseif anything : a = 1else : a = 2print a # prints 2 | Correctness about variable scope |
Python | If I have list1 as shown above , the index of the last value is 3 , but is there a way that if I say list1 [ 4 ] , it would become list1 [ 0 ] ? | list1 = [ 1,2,3,4 ] | Is there a way to cycle through indexes |
Python | I 'm making a wxpython app that I will compile with the various freezing utility out there to create an executable for multiple platforms.the program will be a map editer for a tile-based game enginein this app I want to provide a scripting system so that advanced users can modify the behavior of the program such as mo... | script = textbox.text # bla bla store the stringcode = compile ( script , `` script '' , `` exec '' ) # make the code objecteval ( code , globals ( ) ) | Python - Creating a `` scripting '' system |
Python | I 'm fairly new to programming in general . I need to develop a program that can copy multiple directories at once and also take into account multiple file type exceptions . I came across the shutil module which offers the copytree and ignore_patterns functions . Here is a snippet of my code which also uses the wxPytho... | import osimport wximport wx.lib.agw.multidirdialog as MDDfrom shutil import copytreefrom shutil import ignore_patternsapp = wx.App ( 0 ) dlg = MDD.MultiDirDialog ( None , title= '' Custom MultiDirDialog '' , defaultPath=os.getcwd ( ) , agwStyle=MDD.DD_MULTIPLE|MDD.DD_DIR_MUST_EXIST ) dest = `` Destination Path '' if dl... | Is there a way to interrupt shutil copytree operation in Python ? |
Python | Let 's say I have an async generator like this : I consume it like this : It works just fine , however when the connection is disconnected and there is no new event published the async for will just wait forever , so ideally I would like to close the generator forcefully like this : But I get the following error : Runt... | async def event_publisher ( connection , queue ) : while True : if not await connection.is_disconnected ( ) : event = await queue.get ( ) yield event else : return published_events = event_publisher ( connection , queue ) async for event in published_events : # do event processing here if connection.is_disconnected ( )... | How to forcefully close an async generator ? |
Python | I ’ m new at making COM servers and working with COM from Python so I want to clarify a few things I could not find explicit answers for : Creating GUID ’ s Properly for COM serversDo I generate : The GUID for my intended COM server manually , copy it and use that # for the server from then on in ? Therefore , when I d... | i ) print ( pythoncom.CreateGuid ( ) ) # in interpreterii ) _reg_clsid_ = copy above GUID into your app i ) _reg_clsid_ = pythoncom.CreateGuid ( ) if self.isfile = os.path.isfile ( url ) : load_previous_generated_GUID ( url ) else : # first time running application or setup file is missing GUID = pythoncom.CreateGuid (... | When do I generate new GUID 's for COM Servers ? ( Examples in Python ) |
Python | In NumPy , why does hstack ( ) copy the data from the arrays being stacked : gives for C : whereas hsplit ( ) creates a view on the data : gives for b : I mean - what is the reasoning behind the implementation of this behaviour ( which I find inconsistent and hard to remember ) : I accept that this happens because it '... | A , B = np.array ( [ 1,2 ] ) , np.array ( [ 3,4 ] ) C = np.hstack ( ( A , B ) ) A [ 0 ] =99 array ( [ 1 , 2 , 3 , 4 ] ) a = np.array ( ( ( 1,2 ) , ( 3,4 ) ) ) b , c = np.hsplit ( a,2 ) a [ 0 ] [ 0 ] =99 array ( [ [ 99 ] , [ 3 ] ] ) | Why does hstack ( ) copy data but hsplit ( ) create a view on it ? |
Python | I have installed and tried both wxpython-3.0 and wxpython-2.8 for python2.7 from the standard cygwin repos ( 64-bit , Win 7 ) . However when I start the Cygwin X server and try to run the most simple `` Hello World '' script from wxPython tutorials : I get a Gtk-WARNING ** : Screen for GtkWindow not set which eventuall... | # test.pyimport wxapp = wx.App ( False ) # Create a new app , do n't redirect stdout/stderr to a window.frame = wx.Frame ( None , wx.ID_ANY , `` Hello World '' ) # A Frame is a top-level window.frame.Show ( True ) # Show the frame.app.MainLoop ( ) | Running wxpython app in cygwin/X |
Python | I have the following code : But if I make a subclass of int , and reimplement __cmp__ : Why are these two different ? Is the python runtime catching the TypeError thrown by int.__cmp__ ( ) , and interpreting that as a False value ? Can someone point me to the bit in the 2.x cpython source that shows how this is working... | a = str ( ' 5 ' ) b = int ( 5 ) a == b # False class A ( int ) : def __cmp__ ( self , other ) : return super ( A , self ) .__cmp__ ( other ) a = str ( ' 5 ' ) b = A ( 5 ) a == b # TypeError : A.__cmp__ ( x , y ) requires y to be a ' A ' , not a 'str ' | Does python coerce types when doing operator overloading ? |
Python | Python documentation says : and it gives an example > > > Point = namedtuple ( 'Point ' , ... In all the examples I could find , the return from namedtuple and argument typename are spelled the same . Experimenting , it seems the argument does not matter : What is the distinction ? How does the typename argument matter... | collections.namedtuple ( typename , field_names [ , verbose=False ] [ , rename=False ] ) Returns a new tuple subclass named typename . > > > Class = collections.namedtuple ( 'Junk ' , 'field ' ) > > > obj = Class ( field=1 ) > > > print obj.field1 | What is the difference between namedtuple return and its typename argument ? |
Python | I 'm fairly new in 'recursive functions ' . So , I 'm trying to wrap my head around why we use recursive functions and how recursive functions work and I think I 've a fairly good understanding about it.Two days ago , I was trying to solve the shortest path problem . I 've a following graph ( it 's in python ) : I 'm j... | graph = { ' a ' : [ ' b ' , ' c ' ] , ' b ' : [ ' c ' , 'd ' ] , ' c ' : [ 'd ' ] , 'd ' : [ ' c ' ] , ' e ' : [ ' f ' ] , ' f ' : [ ' c ' ] } def find_path ( graph , start , end , path= [ ] ) : path = path + [ start ] # Just a Test print ( path ) if start == end : return path if start not in graph : return None for no... | How recursive functions work inside a 'for loop ' |
Python | I am using matplotlib ( version 1.4 ) to create images that I need saved in .tiff format . I am plotting in the IPython notebook ( version 3.2 ) with the % matplotlib inline backend . Normally I use the Anaconda distribution and am able to save matplotlib figures to .tiff with no problem . However , I am trying to put ... | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -ValueError Traceback ( most recent call last ) < ipython-input-14-3d911065b472 > in < module > ( ) 56 f.text ( .01 , .38 , `` B '' , size=14 ) 57 -- - > 58 savefig ( f , `` switch_control '' ) < ipython-input... | What other libraries does matplotlib need installed to write tiff files ? |
Python | I have a simple DataFrame : I can then split the tuples column into two very simply , e.g.This approach also works : However if my DataFrame is slightly more complex , e.g.then the first approach throws `` Columns must be same length as key '' ( of course ) because some rows have two values and some have none , and my ... | import pandas as pddf = pd.DataFrame ( { 'id ' : list ( 'abcd ' ) } ) df [ 'tuples ' ] = df.index.map ( lambda i : ( i , i+1 ) ) # outputs : # id tuples # 0 a ( 0 , 1 ) # 1 b ( 1 , 2 ) # 2 c ( 2 , 3 ) # 3 d ( 3 , 4 ) df [ [ ' x ' , ' y ' ] ] = pd.DataFrame ( df.tuples.tolist ( ) ) # outputs : # id tuples x y # 0 a ( 0 ... | Can I split this column containing a mix of tuples/None more efficiently ? |
Python | Will the results of numpy.lib.stride_tricks.as_strided depend on the dtype of the NumPy array ? This question arises from the definition of .strides , which is Tuple of bytes to step in each dimension when traversing an array.Take the following function that I 've used in other questions here . It takes a 1d or 2d arra... | def rwindows ( a , window ) : if a.ndim == 1 : a = a.reshape ( -1 , 1 ) shape = a.shape [ 0 ] - window + 1 , window , a.shape [ -1 ] strides = ( a.strides [ 0 ] , ) + a.strides windows = np.lib.stride_tricks.as_strided ( a , shape=shape , strides=strides ) return np.squeeze ( windows ) # examples # rwindows ( np.arange... | Will results of numpy.as_strided depend on input dtype ? |
Python | I would like to be able to index elements of a power set without expanding the full set into memory ( a la itertools ) Furthermore I want the index to be cardinality ordered . So index 0 should be the empty set , index 2**n - 1 should be all elementsMost literature I have found so far involves generating a power set in... | from scipy.misc import combdef kcombination_to_index ( combination ) : index = 0 combination = sorted ( combination ) for k , ck in enumerate ( combination ) : index += comb ( ck , k+1 , exact=True ) return indexdef index_to_kcombination ( index , k ) : result = [ ] for k in reversed ( range ( 1 , k+1 ) ) : n = 0 while... | Index into size ordered power set |
Python | Python 2.7 : Python 3.5 : How can I get a valid answer ? For me `` .txt '' would fit.Even the filetype lib ca n't handle this : - ( See https : //github.com/h2non/filetype.py/issues/30 | > > > from mimetypes import guess_extension > > > guess_extension ( 'text/plain ' ) '.ksh ' > > > from mimetypes import guess_extension > > > guess_extension ( 'text/plain ' ) '.c ' | content-type text/plain has file extension .ksh ? |
Python | I have a lot of data that I 'd like to structure in a Pandas dataframe . However , I need a multi-index format for this . The Pandas MultiIndex feature has always confused me and also this time I ca n't get my head around it.I built the structure as I want it as a dict , but because my actual data is much larger , I wa... | Participant_n | Task_n | val | dur -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 1 | 1 | 12 | 2 1 | 1 | 3 | 4 1 | 1 | 4 | 12 1 | 2 | 11 | 11 1 | 2 | 34 | 4 import pandas as pdcols = [ 'Participant_n ' , 'Task_n ' , 'val ' , 'dur ' ] data = [ [ 1,1,25,83 ] , [ 1,1,4,68 ] , [ 1,1,9,987 ] , [ 1,2,98,98 ] , [ 1,2,84,4... | Convert dict constructor to Pandas MultiIndex dataframe |
Python | This is my python code which prints the sql query.When printing the Mysql query my Django project shows following error in the terminal : Mysql doumentation does not say much about it.What does this mean and how to can i rectify it . | def generate_insert_statement ( column_names , values_format , table_name , items , insert_template=INSERT_TEMPLATE , ) : return insert_template.format ( column_names= '' , '' .join ( column_names ) , values= '' , '' .join ( map ( lambda x : generate_raw_values ( values_format , x ) , items ) ) , table_name=table_name ... | Mysql 'VALUES function ' is deprecated |
Python | I have three DB models ( from Django ) that can be used as the input for building a recommendation system : Users List - with userId , username , email etcMovies List - with movieId , movieTitle , Topics etcSaves List - with userId , movieId and timestamp ( the current recommendation system will be a little bit simpler... | # usersSet and moviesSet contain only ids of users or movieszeros = numpy.zeros ( shape= ( len ( usersSet ) , len ( moviesSet ) ) , dtype=numpy.int8 ) saves_df = pandas.DataFrame ( zeros , index=list ( usersSet ) , columns=list ( moviesSet ) ) for save in savesFromDb.iterator ( chunk_size=50000 ) : userId = save [ 'use... | Recommendation system with matrix factorization for huge data gives MemoryError |
Python | The documentation on the uuid module says : UUID.variant ¶ The UUID variant , which determines the internal layout of the UUID . This will be one of the integer constants RESERVED_NCS , RFC_4122 , RESERVED_MICROSOFT , or RESERVED_FUTURE.And later : uuid.RESERVED_NCS ¶ Reserved for NCS compatibility . uuid.RFC_4122 ¶ Sp... | > > > import uuid > > > u = uuid.uuid4 ( ) > > > u.variant'specified in RFC 4122 ' > > > uuid.RESERVED_NCS'reserved for NCS compatibility ' > > > uuid.RFC_4122'specified in RFC 4122 ' > > > uuid.RESERVED_MICROSOFT'reserved for Microsoft compatibility ' > > > uuid.RESERVED_FUTURE'reserved for future definition ' RESERVE... | When would a UUID variant be an integer ? |
Python | I 'm working with Keras and I 'm trying to rewrite categorical_crossentropy by using the Keras abstract backend , but I 'm stuck . This is my custom function , I want just the weighted sum of crossentropy : In my program I generate a label_pred with to model.predict ( ) .Finally I do : I get the following error : | def custom_entropy ( y_true , y_pred ) : y_pred /= K.sum ( y_pred , axis=-1 , keepdims=True ) # clip to prevent NaN 's and Inf 's y_pred = K.clip ( y_pred , K.epsilon ( ) , 1 - K.epsilon ( ) ) loss = y_true * K.log ( y_pred ) loss = -K.sum ( loss , -1 ) return loss label_pred = model.predict ( mfsc_train [ : , : ,5 ] )... | Keras crossentropy |
Python | I have a field in the model , and the data entered is , the django model 's max_length is set to 2000 while the entered data is only of length 3 , Does the max_length reserves space for 2000 characters in the database table per object ? after the model object is saved , does the space is freed up ? Do setting up higher... | name = models.CharField ( max_length=2000 ) name='abc ' | do setting the max_length to a very large value consume extra space ? |
Python | This returns only result [ 89 ] and I need to return the whole 89 % . Any ideas how to do it please ? | re.findall ( `` ( 100| [ 0-9 ] [ 0-9 ] | [ 0-9 ] ) % '' , `` 89 % '' ) | Python - re.findall returns unwanted result |
Python | I 'm having a bit of trouble understanding why some variables are local and some are global . E.g . when I try this : I get this error : Now , it totally makes sense to me why it 's throwing me an error on score . I did n't set it globally ( I commented that part out intentionally to show this ) . And I am specifically... | from random import randintscore = 0choice_index_map = { `` a '' : 0 , `` b '' : 1 , `` c '' : 2 , `` d '' : 3 } questions = [ `` What is the answer for this sample question ? `` , `` Answers where 1 is a , 2 is b , etc . `` , `` Another sample question ; answer is d. '' ] choices = [ [ `` a ) choice 1 '' , `` b ) choic... | Why some Python variables stay global , while some require definition as global |
Python | This code returns a list [ 0,0,0 ] to [ 9,9,9 ] , which produces no repeats and each element is in order from smallest to largest.Looking for a shorter and better way to write this code without using multiple variables ( position1 , position2 , position3 ) , instead only using one variable i.Here is my attempt at modif... | def number_list ( ) : b= [ ] for position1 in range ( 10 ) : for position2 in range ( 10 ) : for position3 in range ( 10 ) : if position1 < =position2 and position2 < =position3 : b.append ( [ position1 , position2 , position3 ] ) return b def number_list ( ) : b= [ ] for i in range ( 1000 ) : b.append ( map ( int , st... | Number list with no repeats and ordered |
Python | I 'm trying to handle a file , and I need to remove extraneous information in the file ; notably , I 'm trying to remove brackets [ ] including text inside and between bracket [ ] [ ] blocks , Saying that everything between these blocks including them itself but print everything outside it . Below is my text File with ... | $ cat smbHi this is my config file.Please dont delete it [ homes ] browseable = No comment = Your Home create mode = 0640 csc policy = disable directory mask = 0750 public = No writeable = Yes [ proj ] browseable = Yes comment = Project directories csc policy = disable path = /proj public = No writeable = Yes [ ] This ... | Python remove Square brackets and extraneous information between them |
Python | First I 'll lay out what I 'm trying to achieve in case there 's a different way to go about it ! I want to be able to edit both sides of an M2M relationship ( preferably on the admin page although if needs be it could be on a normal page ) using any of the multi select interfaces.The problem obviously comes with the r... | # models.pyclass Tag ( models.Model ) : name = models.CharField ( max_length=200 ) class Project ( models.Model ) : name = models.CharField ( max_length=200 ) description = models.TextField ( ) tags = models.ManyToManyField ( Tag , related_name='projects ' ) # admin.pyclass TagForm ( ModelForm ) : fields = ( 'name ' , ... | Editing both sides of M2M in Admin Page |
Python | I have a square 2D numpy array , A , and an array of zeros , B , with the same shape.For every index ( i , j ) in A , other than the first and last rows and columns , I want to assign to B [ i , j ] the value of np.sum ( A [ i - 1 : i + 2 , j - 1 : j + 2 ] .Example : Is there an efficient way to do this ? Or should I s... | A =array ( [ [ 0 , 0 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 1 , 0 ] , [ 0 , 1 , 1 , 0 , 0 ] , [ 0 , 1 , 0 , 1 , 0 ] , [ 0 , 0 , 0 , 0 , 0 ] ) B =array ( [ [ 0 , 0 , 0 , 0 , 0 ] , [ 0 , 3 , 4 , 2 , 0 ] , [ 0 , 4 , 6 , 3 , 0 ] , [ 0 , 3 , 4 , 2 , 0 ] , [ 0 , 0 , 0 , 0 , 0 ] ) | 2d numpy array , making each value the sum of the 3x3 square it is centered at |
Python | I 'm trying to create a dictionary in OCaml that maps a string to a list of strings . I 've referenced this tutorial for a basic string to string map , but I need some help making a list.Here is what I want to do in Python : Thanks in advance | > > > food = { } > > > food [ `` fruit '' ] = ( `` blueberry '' , `` strawberry '' , `` kiwi '' ) > > > food [ `` veggie '' ] = ( `` broccoli '' , `` kale '' ) > > > for k in food : ... for v in food [ k ] : ... print k , `` -- > '' , v ... fruit -- > blueberryfruit -- > strawberryfruit -- > kiwiveggie -- > broccoliveg... | OCaml map a string to a list of strings |
Python | I am aware of the nature of floating point math but I still find the following surprising : From the documentation I could not find anything that would explain that . It does state : ... In addition , any string that represents a finite value and is accepted by the float constructor is also accepted by the Fraction con... | from fractions import Fractionprint ( Fraction ( 0.2 ) ) # - > 3602879701896397/18014398509481984print ( Fraction ( str ( 0.2 ) ) ) # - > 1/5print ( Fraction ( 0.2 ) ==Fraction ( str ( 0.2 ) ) ) # returns Falseprint ( 0.2 == float ( str ( 0.2 ) ) ) # but this returns True ! from fractions import Fractionfor x in range ... | fractions.Fraction ( ) returns different nom. , denom . pair when parsing a float or its string representation |
Python | I 'm trying to create in Altair a Vega-Lite specification of a plot of a time series whose time range spans a few days . Since in my case , it will be clear which day is which , I want to reduce noise in my axis labels by letting labels be of the form ' % H : % M ' , even if this causes labels to be non-distinct.Here '... | import altair as altimport numpy as npimport pandas as pd # Create data spanning 30 hours , or just over one full daydf = pd.DataFrame ( { 'time ' : pd.date_range ( '2018-01-01 ' , periods=30 , freq= ' H ' ) , 'data ' : np.arange ( 30 ) **.5 } ) alt.Chart ( df ) .mark_line ( ) .encode ( x='yearmonthdatehoursminutes ( t... | Hours and minutes as labels in Altair plot spanning more than one day |
Python | how can a delete a specific entry from a bibtex file based on a cite key using python ? I basically want a function that takes two arguments ( path to bibtex file and cite key ) and deletes the entry that corresponds to the key from the file . I played around with regular expressions but was n't successful . I also loo... | def deleteEntry ( path , key ) : # get content of bibtex file f = open ( path , ' r ' ) content = f.read ( ) f.close ( ) # delete entry from content string content_modified = # rewrite file f = open ( path , ' w ' ) f.write ( content_modified ) f.close ( ) @ article { dai2008thebigfishlittlepond , title = { The { Big-F... | deleting a specific entry from a bibtex file based on cite key using Python |
Python | I 'm querying the Windows Desktop Search JET ( ESE ) database using Python + ADO . It works but after ~7600 records I get an exception when advancing to the next record using MoveNext . I know it is not at EOF because I can run the same query in VBScript and get way more records with the same query.Exception tracebackQ... | Traceback ( most recent call last ) : File `` test_desktop_search.py '' , line 60 , in < module > record_set.MoveNext ( ) File `` < COMObject ADODB.Recordset > '' , line 2 , in MoveNextpywintypes.com_error : ( -2147352567 , 'Exception occurred . ' , ( 0 , None , None , None , 0 , -2147215865 ) , None ) Exception from H... | How to use win32com to handle overflow when querying Desktop Search ? |
Python | tl ; dr : How do I predict the shape returned by numpy broadcasting across several arrays without having to actually add the arrays ? I have a lot of scripts that make use of numpy ( Python ) broadcasting rules so that essentially 1D inputs result in a multiple-dimension output . For a basic example , the ideal gas law... | def rhoIdeal ( pressure , temperature ) : rho = np.zeros_like ( pressure + temperature ) rho += pressure / ( 287.05 * temperature ) return rho rhoIdeal ( pressure [ : ,np.newaxis ] , temperature [ np.newaxis , : ] ) def returnShape ( list_of_arrays ) : return np.zeros_like ( sum ( list_of_arrays ) ) .shape | Numpy function to get shape of added arrays |
Python | I have a template in which I placed , let 's say 5 forms , but all disabled to be posted except for the first one . The next form can only be filled if I click a button that enables it first.I 'm looking for a way to implement a Django-like forloop.last templatetag variable in a for loop inside an acceptance test to de... | for form_data in step.hashes : # get and fill the current form with data in form_data if not forloop.last : # click the button that enables the next form # submit all filled forms | Is there a pythonic way of knowing when the first and last loop in a for is being passed through ? |
Python | We trained this model for classify 5 image classes . We used 500 images for each class for train the model and 200 images for each class to validate the model . We used keras in tensorflow backend.It uses data that can be downloaded at : https : //www.kaggle.com/alxmamaev/flowers-recognitionIn our setup , we : created ... | from keras.preprocessing.image import ImageDataGeneratorfrom keras.models import Sequentialfrom keras.layers import Conv2D , MaxPooling2Dfrom keras.layers import Activation , Dropout , Flatten , Densefrom keras import backend as K # dimensions of our images.img_width , img_height = 150 , 150train_data_dir = 'flowers/tr... | Image Classification with TensorFlow and Keras |
Python | I have two dataframes I would like to merge.DF1 has this formDF2 is another set of data , which shares a condensed version of the indexI would like to populate DF1 with the data from DF2What is the most efficient way to do this ? | index c1 c2a1 1 2a1 2 1a1 3 1b1 5 2b1 4 7 index c3 c4a1 9 10b1 7 8 index c1 c2 c3 c4a1 1 2 9 10a1 2 1 9 10a1 3 1 9 10b1 5 2 7 8b1 4 7 7 8 | Expand and merge Pandas dataframes |
Python | I am a bit puzzled by the python ( 2.7 ) list.remove function . In the documentation of remove it says : `` Remove the first item from the list whose value is x . It is an error if there is no such item . `` So , I guess here value means that comparison is based on equality ( i.e . == ) and not identity ( i.e . is ) . ... | import numpy as npx = np.array ( [ 1,2,3 ] ) mylist = [ x , 42 , 'test ' , x ] # list containing the numpy array twiceprint mylist [ array ( [ 1 , 2 , 3 ] ) , 42 , 'test ' , array ( [ 1 , 2 , 3 ] ) ] mylist.remove ( x ) print mylist [ 42 , 'test ' , array ( [ 1 , 2 , 3 ] ) ] mylist.remove ( x ) -- -- -- -- -- -- -- -- ... | Removal of an item from a python list , how are items compared ( e.g . numpy arrays ) ? |
Python | I transformed the following functionto a batched versionThis function handles quaternion1 and quaternion0 with shape ( ? ,4 ) . Now I want that the function can handle an arbitrary number of dimensions , such as ( ? , ? ,4 ) . How to do this ? | def quaternion_multiply ( quaternion0 , quaternion1 ) : `` '' '' Return multiplication of two quaternions . > > > q = quaternion_multiply ( [ 1 , -2 , 3 , 4 ] , [ -5 , 6 , 7 , 8 ] ) > > > numpy.allclose ( q , [ -44 , -14 , 48 , 28 ] ) True `` '' '' x0 , y0 , z0 , w0 = quaternion0 x1 , y1 , z1 , w1 = quaternion1 return ... | Numpy : make batched version of quaternion multiplication |
Python | Playing around with id ( ) . Began with looking at the addresses of identical attributes in non-identical objects . But that does n't matter now , I guess . Down to the code : First test ( in interactive console ) : No surprise here , actually . n.__class__ is different than t.__class__ so it seems obvious they ca n't ... | class T ( object ) : passclass N ( object ) : pass n = N ( ) t = T ( ) id ( n ) # prints 4298619728id ( t ) # prints 4298619792 > > > n1 = N ( ) > > > n2 = N ( ) > > > id ( n1 ) == id ( n2 ) False > > > id ( N ( ) ) 4298619728 > > > id ( N ( ) ) 4298619792 > > > id ( N ( ) ) 4298619728 > > > id ( N ( ) ) 4298619792 > >... | Python memory management insights -- id ( ) |
Python | This behavior is a little bit strange to me , I always thought x/=5 . was equivalent to x=x/5 . . But clearly the g ( x ) function does not create a new reference with /= operation . Could anyone offer an explanation for this ? | def f ( x ) : x=x/5 . return xdef g ( x ) : x/=5 . return xx_var = np.arange ( 5 , dtype=np.double ) f ( x_var ) print x_varg ( x_var ) print x_varOutput : [ 0 . 1 . 2 . 3 . 4 . ] [ 0 . 0.2 0.4 0.6 0.8 ] | Unexpected behavior for numpy self division |
Python | I have a large file ( 2GB ) of categorical data ( mostly `` Nan '' -- but populated here and there with actual values ) that is too large to read into a single data frame . I had a rather difficult time coming up with a object to store all the unique values for each column ( Which is my goal -- eventually I need to fac... | import pandas as pd # large file of csv separated text datadata=pd.read_csv ( `` ./myratherlargefile.csv '' , chunksize=100000 , dtype=str ) collist= [ ] master= [ ] i=0initialize=0for chunk in data : # so the first time through I have to make the `` master '' list if initialize==0 : for col in chunk : # thinking about... | The Pythonic way to grow a list of lists |
Python | What is the best data structure to have a both-ways mapping of object , with flag values for each couple , in Python ? For instance , let 's imagine I have two pools of men and women I want to match together . I want a datastructure to store de matches so I can access the corresponding man of each woman , the correspon... | couples = bidict ( { 'leonard ' : 'penny ' , 'howard ' : 'bernadette ' , 'sheldon ' : 'amy ' } ) couples.forceput ( 'stephen ' , 'amy ' ) print couples > > bidict ( { 'stephen ' : 'amy ' , 'leonard ' : 'penny ' , 'howard ' : 'bernadette ' } ) quality ( 'stephen ' , 'amy ' ) > > 0.4couples.forceput ( 'sheldon ' , 'amy '... | Efficient both ways mapping in Python with flag values |
Python | I am using python 3.6.5 and plotly 3.9.0 to create an interactive line graph that the user can change the range using a ranger slide . I would like to add a hover tool to the range slider so that when the user moves the slider , a hover icon says the new date range before the user releases the mouse . I think this is t... | import dashimport dash_core_components as dccimport dash_html_components as htmlimport plotly.graph_objs as goimport plotly.plotly as pyfrom datetime import datetimeimport pandas as pdimport numpy as npnp.random.seed ( 10 ) df = pd.DataFrame ( { 'date ' : pd.date_range ( start= ' 1/1/2000 ' , periods=200 ) , ' x ' : np... | Hover tool for plotly slider widget ( python ) |
Python | Is there a way to import numpy without installing it ? I have a general application built into an .exe with PyInstaller . The application has a plugin system which allows it to be extended through Python scripts . The plugin import system works fine for basic modules ( lone .py files , classes , functions , and simple ... | import syssys.path.append ( r '' C : \path\to\numpy-1.16.3+mkl-cp36-cp36m-win_amd64.whl '' ) import numpy as np *** ImportError : IMPORTANT : PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE ! Importing the multiarray numpy extension module failed . Mostlikely you are trying to import a failed build of numpy.Here... | Import numpy without installing |
Python | I have a data frame like thisI want to filter all the 'None ' from col1 and add the corresponding col2 value into a new column col3 . My output look like this Can anyone help me to achieve this . | ID col1 col2 1 Abc street 2017-07-27 1 None 2017-08-17 1 Def street 2018-07-15 1 None 2018-08-13 2 fbg street 2018-01-07 2 None 2018-08-12 2 trf street 2019-01-15 ID col1 col2 col3 1 Abc street 2017-07-27 2017-08-17 1 Def street 2018-07-15 2018-08-13 2 fbg street 2018-01-07 2018-08-12 2 trf street 2019-01-15 | Filter a data-frame and add a new column according to the given condition |
Python | When adding an integer value to a float value , I realized that __add__ method is working fine if called on float , such as this : but not if called on an integer : At first I thought that __add__ was just being implemented differently for int and float types ( like float types accepting to be added to int types , but ... | > > > n = 2.0 > > > m = 1 > > > n.__add__ ( m ) 3.0 > > > m.__add__ ( n ) NotImplemented > > > n + m3.0 > > > m + n3.0 | Python : __add__ and + , different behavior with float and integer |
Python | Is it common in Python to keep testing for type values when working in a OOP fashion ? Or I can use a more loose approach , like : | class Foo ( ) : def __init__ ( self , barObject ) : self.bar = setBarObject ( barObject ) def setBarObject ( barObject ) ; if ( isInstance ( barObject , Bar ) : self.bar = barObject else : # throw exception , log , etc.class Bar ( ) : pass class Foo ( ) : def __init__ ( self , barObject ) : self.bar = barObjectclass Ba... | Is it common/good practice to test for type values in Python ? |
Python | I am trying to divide a rectangle with specific coordinates into 8 smaller rectangles ( two columns and four rows ) is this possible ? Input for example would be : and result would be : This is what I 've tried so far : This is what I need ( kind of : / ) : | rec = [ ( 0 , 0 ) , ( 0 , 330 ) , ( 200 , 330 ) , ( 200 , 0 ) ] res = [ [ ( 0 , 0 ) , ( 0 , 82 ) , ( 100 , 82 ) , ( 100 , 0 ) ] , [ ( 0 , 82 ) , ( 0 , 164 ) , ( 100 , 164 ) , ( 100 , 82 ) ] , ... ... . ] h = 330w = 200offsets = [ ( 0 , 0 ) , ( 400 , 0 ) , ( 0 , 500 ) , ( 400 , 500 ) ] blisters = [ ] for offset in offse... | How to divide a rectangle in specific number of rows and columns ? |
Python | For example , here is a simple c function that use pointer to return value : I want to call add ( ) function for every elements in two arrays , and collect the result by numba @ jit function.Compile the c code first : And load it by ctypes : then the numba function : But numba has no addressof operator or function.Curr... | void add ( double x , double y , double *r ) { *r = x + y ; } ! gcc -c -fpic func.c ! gcc -shared -o func.so func.o lib = ctypes.cdll.LoadLibrary ( `` ./func.so '' ) add = lib.addadd.argtypes = ctypes.c_double , ctypes.c_double , ctypes.c_void_padd.restype = None from numba import jit , float64 @ jit ( float64 ( float6... | How to call ctypes functions that use pointer to return value in Numba @ jit |
Python | Let us have the following example : This code works fine and I have the following output : Now lets pass the value as bytes : This also works fine and have the following output : But things change when I try to have the key as bytes : This results in TypeError saying : Is there any way we can pass bytes as keyword argu... | def fun ( **args ) : print ( str ( args ) ) dic = { 'name ' : 'Pulkit ' } fun ( **dic ) { 'name ' : 'Pulkit ' } dic_vb = { 'name ' : b'Pulkit ' } fun ( **dic_vb ) { 'name ' : b'Pulkit ' } dic_kb = { b'name ' : 'Pulkit ' } TypeError : fun ( ) keywords must be strings | How can we pass bytes as the key of keyword arguments to functions ? |
Python | I 'm trying to merge two dataframes in pandas on a common column name ( orderid ) . The resulting dataframe ( the merged dataframe ) is dropping the orderid from the 2nd data frame . Per the documentation , the 'on ' column should be kept unless you explicitly tell it not to . Which outputs this : What I am trying to c... | import pandas as pd df = pd.DataFrame ( [ [ 1 , ' a ' ] , [ 2 , ' b ' ] , [ 3 , ' c ' ] ] , columns= [ 'orderid ' , 'ordervalue ' ] ) df [ 'orderid ' ] = df [ 'orderid ' ] .astype ( str ) df2 = pd.DataFrame ( [ [ 1,200 ] , [ 2 , 300 ] , [ 3 , 400 ] , [ 4,500 ] ] , columns= [ 'orderid ' , 'ordervalue ' ] ) df2 [ 'orderi... | Pandas merge not keeping 'on ' column |
Python | I 'm going to write my own Python-Java interface . It is compiled as a DLL andwrapped using ctypes.Yet , it is possible to find Java-classes and allocate Java-objects.But what would be an interface to another language without using those objectsmethods ? My aim is to make this as natural as possible . Unfortunately , i... | mainMethod = JMethod ( 'main ' , JStringArray ) JInt = JClass ( 'java/lang/Integer ' ) JShort = JClass ( 'java/lang/Short ' ) JString = JClass ( 'java/lang/String ' ) | My Python-Java Interface , good design ? And how to wrap JNI Functions ? |
Python | There are two files : And : When executed with Python 2.7 : When executed with Python 3.5 : What is that weird thing < frozen importlib._bootstrap > all about ? What happened with import and/or inspect that changed this behaviour ? How can we get that Python 2 filename introspection working again on Python 3 ? | # the_imported.pyimport inspectimported_by_fname = inspect.currentframe ( ) .f_back.f_code.co_filenameprint ( ' { } was imported by { } '.format ( __name__ , imported_by_fname ) ) # the_importer.pyimport the_imported $ python the_importer.py the_imported was imported by the_importer.py $ python3 the_importer.py the_imp... | inspect who imported me |
Python | When two bar charts ( one horizontal , one vertical ) are shown side-by-side using alt.hconcat , the titles are misaligned even though the heights of the charts are equal . Is there a way to align the titles ? The chart titles are misaligned . ( ca n't post the image since I apparently need 10 reputation points to do s... | # Makes test dataframetest = pd.DataFrame ( { `` group '' : [ `` a '' , '' b '' , '' c '' ] , '' value1 '' : [ 4,5,6 ] , `` value2 '' : [ 10,12,14 ] } ) .reset_index ( ) # Sets up vertical bar chartchart1 = alt.Chart ( test ) .mark_bar ( ) .encode ( x = alt.X ( 'group : N ' ) , y = alt.Y ( 'value1 : Q ' ) ) .properties... | Is there a way to align chart titles when ` hconcat ` is used ? |
Python | tl ; dr -- In a PySide application , an object whose method throws an exception will remain alive even when all other references have been deleted . Why ? And what , if anything , should one do about this ? In the course of building a simple CRUDish app using a Model-View-Presenter architecture with a PySide GUI , I di... | import loggingimport sysimport weakreffrom PySide import QtGuiclass InnerPresenter : def __init__ ( self , view ) : self._view = weakref.ref ( view ) self.logger = logging.getLogger ( 'InnerPresenter ' ) self.logger.debug ( 'Initializing InnerPresenter ( id : % s ) ' % id ( self ) ) def __del__ ( self ) : self.logger.d... | Why is PySide 's exception handling extending this object 's lifetime ? |
Python | I am trying to read a website 's content using below code.In the result , I am unable to see the the table which I could see when I do `` Inspect '' element manually in the browser.Using selenium could be one solution . But I am looking for some other alternate solutions , if possible.Any idea on how to read the data f... | import requestsfrom bs4 import BeautifulSoupurl = `` https : //chartink.com/screener/test-121377 '' r = requests.get ( url ) data = r.textsoup = BeautifulSoup ( data , '' html.parser '' ) print ( soup ) | Unable to read table from website using Beautifulsoup |
Python | I have the following code : Since MyObject inherits from object , why does n't MyCallableSubclass work in every place that MyCallable does ? I 've read a bit about the Liskov substitution principle , and also consulted the Mypy docs about covariance and contravariance . However , even in the docs themselves , they give... | from typing import CallableMyCallable = Callable [ [ object ] , int ] MyCallableSubclass = Callable [ [ 'MyObject ' ] , int ] def get_id ( obj : object ) - > int : return id ( obj ) def get_id_subclass ( obj : 'MyObject ' ) - > int : return id ( obj ) def run_mycallable_function_on_object ( obj : object , func : MyCall... | How to make Mypy deal with subclasses in functions as expected |
Python | I am trying to set up a subclass of pd.DataFrame that has two required arguments when initializing ( group and timestamp_col ) . I want to run validation on those arguments group and timestamp_col , so I have a setter method for each of the properties . This all works until I try to set_index ( ) and get TypeError : 'N... | import pandas as pdimport numpy as npclass HistDollarGains ( pd.DataFrame ) : @ property def _constructor ( self ) : return HistDollarGains._internal_ctor _metadata = [ `` group '' , `` timestamp_col '' , `` _group '' , `` _timestamp_col '' ] @ classmethod def _internal_ctor ( cls , *args , **kwargs ) : kwargs [ `` gro... | Property Setter for Subclass of Pandas DataFrame |
Python | How can I get the second minimum value from each column ? I have this array : I wish to have output like : | A = [ [ 72 76 44 62 81 31 ] [ 54 36 82 71 40 45 ] [ 63 59 84 36 34 51 ] [ 58 53 59 22 77 64 ] [ 35 77 60 76 57 44 ] ] A = [ 54 53 59 36 40 44 ] | Get second minimum values per column in 2D array |
Python | Python 3.7.2 , though I doubt that piece of information would be very useful.Pygame 1.7.2 . I 'm using this mainly to draw the triangulation . All calculations are done with plain formulas.The pseudocode for the Bowyer-Watson algorithm is as shown , according to Wikipedia : However , when I run my code , while it remov... | function BowyerWatson ( pointList ) // pointList is a set of coordinates defining the points to be triangulated triangulation : = empty triangle mesh data structure add super-triangle to triangulation // must be large enough to completely contain all the points in pointList for each point in pointList do // add all the... | A Bowyer-Watson Delaunay Triangulation I implemented does n't remove the triangles that contain points of the super-triangle |
Python | I 'm currently in the process of writing a client server app as an exercise and I 've gotten pretty much everything to work so far , but there is a mental hurdle that I have n't been able to successfully google myself over . In the server application am I correct in my thinking that threading the packet handler and dat... | class socketListen ( threading.Thread ) : def run ( self ) : while True : datagram = s.recv ( '1024 ' ) if not datagram : break packetArray = datagram.split ( ' , ' ) if packetArray [ 0 ] = '31337 ' : listHandle.put ( packetArray ) s.close ( ) class stackOperations ( threading.Thread ) : def run ( self ) : while True :... | Python Threading Concept Question |
Python | I 'm trying to fetch data returned from url . Curl to the url results in following : [ { `` name '' : `` Hello World ! `` } ] Following is the code in my App.jsMy contact.js contains the following : The data does not get rendered or logged . Is there an issue in the way I 'm fetching it ? EDIT : The issue is related to... | import React , { Component } from 'react ' ; import Contacts from './components/contacts ' ; class App extends Component { render ( ) { return ( < Contacts contacts= { this.state.contacts } / > ) } state = { contacts : [ ] } ; componentDidMount ( ) { fetch ( 'url ' ) .then ( res = > res.json ( ) ) .then ( ( data ) = > ... | React not reading json returned from flask GET endpoint |
Python | I created the requirements.txt with pip freeze > requirements.txt . Some modules show the @ file ... .. instead of the version # . What does it mean and why it show ? Conda : 4.8.3Here is the result of requirements.txt . e.g . astroid , flask-admin , matplotlib shows `` @ file '' belowHere is the conda listFinally I pl... | astroid @ file : ///opt/concourse/worker/volumes/live/b22b518b-f584-4586-5ee9-55bfa4fca96e/volume/astroid_1592495912194/workbcrypt==3.1.7blinker==1.4certifi==2020.6.20cffi==1.14.0click==7.1.2cycler==0.10.0dnspython==1.16.0ecdsa==0.13email-validator @ file : ///home/conda/feedstock_root/build_artifacts/email_validator_1... | Why does the pip requirements file contain `` @ file '' instead of version number ? |
Python | I 'm using ConfigObj in python with Template-style interpolation . Unwrapping my config dictionary via ** does n't seem to do interpolation . Is this a feature or a bug ? Any nice workarounds ? I 'd expect the second line to be /test/directory . Why does n't interpolation work with **kwargs ? | $ cat my.conffoo = /testbar = $ foo/directory > > > import configobj > > > config = configobj.ConfigObj ( 'my.conf ' , interpolation='Template ' ) > > > config [ 'bar ' ] '/test/directory ' > > > ' { bar } '.format ( **config ) ' $ foo/directory ' | Why does n't **kwargs interpolate with python ConfigObj ? |
Python | In Python one can iterate over multiple variables simultaneously like this : Is there a C # analog closer than this ? Edit - Just to clarify , the exact code in question was having to assign a name to each index in the C # example . | my_list = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] for a , b , c in my_list : pass List < List < int > > myList = new List < List < int > > { new List < int > { 1 , 2 , 3 } , new List < int > { 4 , 5 , 6 } } ; foreach ( List < int > subitem in myList ) { int a = subitem [ 0 ] ; int b = subitem [ 1 ] ; int c = subitem [ 2 ] ; ... | C # analog of multi-variable iteration in Python ? |
Python | I am using scrapy 1.1 to scrape a website . The site requires periodic relogin . I can tell when this is needed because when login is required a 302 redirection occurs . Based on # http : //sangaline.com/post/advanced-web-scraping-tutorial/ , I have subclassed the RedirectMiddleware , making the location http header av... | request.meta [ 'redirect_urls ' ] def test1 ( self , response ) : ... ... for row in empties : # 100 records d = object_as_dict ( row ) AA yield Request ( url=myurl , headers=self.headers , callback=self.parse_lookup , meta= { d ' : d } , dont_filter=True ) def parse_lookup ( self , response ) : if 'redirect_urls ' in ... | Scrapy : Sending information to prior function |
Python | I am just getting into Python coding and I 'm wondering which is considered more pythonic ? Example A : An obvious main method.or Example B : No main method.Any help/pointers would be appreciated ? | # ! /usr/bin/env python -ttimport randomdef dice_roll ( num=1 ) : for _ in range ( num ) : print ( `` Rolled a '' , random.randrange ( 1,7,1 ) ) def main ( ) random.seed ( ) try : num = int ( input ( `` How many dice ? `` ) ) dice_roll ( num ) except ValueError : print ( `` Non-numeric Input '' ) if __name__ == '__main... | Main functions , pythonic ? |
Python | I have a class that connects three other services , specifically designed to make implementing the other services more modular , but the bulk of my unit test logic is in mock verification . Is there a way to redesign to avoid this ? Python example : I then have to mock input , output and finder . Even if I do make anot... | class Input ( object ) : passclass Output ( object ) : passclass Finder ( object ) : passclass Correlator ( object ) : pass def __init__ ( self , input , output , finder ) : pass def run ( ) : finder.find ( input.GetRows ( ) ) output.print ( finder ) | Is having a unit test that is mostly mock verification a smell ? |
Python | So I have this code for an object . That object being a move you can make in a game of rock papers scissor.Now , the object needs to be both an integer ( for matching a protocol ) and a string for convenience of writing and viewing.Now I 'm kinda new to python , coming from a C and Java background.A big thing in python... | class Move : def __init__ ( self , setMove ) : self.numToName = { 0 : '' rock '' , 1 : '' paper '' ,2 : '' scissors '' } self.nameToNum = dict ( reversed ( pairing ) for pairing in self.numToName.items ( ) ) if setMove in self.numToName.keys ( ) : self.mMove=setMove else : self.mMove=self.nameToNum.get ( setMove ) # ma... | How can I make this code Pythonic |
Python | I have a pandas DataFrame with a two-level multiindex . The second level is numeric and supposed to be sorted and sequential for each unique value of the first-level index , but has gaps . How do I insert the `` missing '' rows ? Sample input : Expected output : I suspect I could have used resample , but I am having tr... | import pandas as pddf = pd.DataFrame ( list ( range ( 5 ) ) , index=pd.MultiIndex.from_tuples ( [ ( ' A',1 ) , ( ' A',3 ) , ( ' B',2 ) , ( ' B',3 ) , ( ' B',6 ) ] ) , columns='value ' ) # value # A 1 0 # 3 1 # B 2 2 # 3 3 # 6 4 # value # A 1 0 # 2 NaN # 3 1 # B 2 2 # 3 3 # 4 NaN # 5 NaN # 6 4 | Inserting `` missing '' multiindex rows into a Pandas Dataframe |
Python | I 've struck a problem with a regular expression in Python ( 2.7.9 ) I 'm trying to strip out HTML < span > tags using a regex like so : re.sub ( r ' < span [ ^ > ] * > ( .* ? ) < /span > ' , r'\1 ' , input_text , re.S ) ( the regex reads thusly : < span , anything that 's not a > , then a > , then non-greedy-match any... | # ! /usr/bin/env pythonimport retext1 = ' < body id= '' aa '' > this is a < span color= '' red '' > test\n with newline < /span > < /body > 'print repr ( text1 ) text2 = re.sub ( r ' < span [ ^ > ] * > ( .* ? ) < /span > ' , r'\1 ' , text1 , re.S ) print repr ( text2 ) # ! /usr/bin/perl $ text1 = ' < body id= '' aa '' ... | python re.sub non-greed substitute fails with a newline in the string |
Python | Simple Problem Statement : Is is possible to have a array of a custom size data type ( 3/5/6/7 byte ) in C or Cython ? Background : I have run across a major memory inefficiency while attempting to code a complex algorithm . The algorithm calls for the storage of a mind-blowing amount of data . All the data is arranged... | def to_bytes ( long long number , int length ) : cdef : list chars = [ ] long long m long long d for _ in range ( length ) : m = number % 256 d = number // 256 chars.append ( m ) number = d cdef bytearray binary = bytearray ( chars ) binary = binary [ : :-1 ] return binarydef from_bytes ( string ) : cdef long long d = ... | Custom size array |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.