lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | When I runit locks my system up until I can do a Ctrl+C if I run it as a Python script from the shell , and running it from the interpreter made me have to hard shutdown my laptop.However , works fine and gives the expected result.Why does this happen ? At first , I thought it might be because I was trying to extend a ... | a = [ ' a ' ] a.extend ( map ( lambda x : ' b ' + x , a ) ) a = [ ' a ' ] a.extend ( list ( map ( lambda x : ' b ' + x , a ) ) ) a = [ ' a ' ] tmp = map ( lambda x : ' b ' + x , a ) a.extend ( tmp ) a = [ ' a ' ] tmp = list ( map ( lambda x : ' b ' + x , a ) ) a.extend ( tmp ) | Why does this Python code ( compositing a list extension with a map of itself ) make my system freeze up ? |
Python | I was looking at some code with two __import__ statements , and the second __import__ statement does n't work unless the first one has already been run.The directory structure is like this : The code has two __import__ statements : The first one makes sense - it is roughly the equivalent of doingbut allows for the subd... | dir1 |-__init__.py |-subdir1 | |-__init__.py | |-file1.py | |-file2.py | |-subdir2 |-__init__.py |-file1.py |-file2.py m = __import__ ( 'dir1 . '+subdir1 , fromlist= [ file1 ] ) ... m = __import__ ( file2 , fromlist= [ class_inside_file2 ] ) from dir1.subdir1 import file1 from file2 import class_inside_file2 | Why does one __import__ statement affect the validity of the next one ? |
Python | I have a decorator that takes a function and returns the same function with some added attributes : How do I type hint the return value of decorator ? I want the type hint to convey two pieces of information : the return value is a Callablethe return value has attributes attr1 and attr2If I write a protocol , then I lo... | import functoolsfrom typing import *def decorator ( func : Callable ) - > Callable : func.attr1 = `` spam '' func.attr2 = `` eggs '' return func class CallableWithAttrs ( Protocol ) : attr1 : str attr2 : str class CallableWithAttrs ( Callable , Protocol ) : attr1 : str attr2 : str error : Invalid base class `` Callable... | How to combine a custom protocol with the Callable protocol ? |
Python | I 've got a situation where I have several items I 'd like to open using a with block . In my case , these are external hardware devices which require some clean-up when closed -- but that does n't really matter for the point at hand.Assuming a class something like : I would ( given a fixed number of Controllers ) , do... | class Controller ( object ) : def __init__ ( self , name ) : self._name = name def __enter__ ( self ) : # Do some work on entry print ( `` Entering '' , self._name ) return self def __exit__ ( self , type , value , traceback ) : # Clean up ( restoring external state , turning off hardware , etc ) print ( `` Exiting '' ... | Is it possible to open an arbitrary number of items using ` with ` in python ? |
Python | I 'm coming from a C++ background to pythonI have been declaring member variables and setting them in a C++esqe way like so : Then I noticed in some open source code , that the initial declaration my_member = [ ] was completely left out and only created in the constructor.Which obviously is possible as python is dynami... | class MyClass : my_member = [ ] def __init__ ( self , arg_my_member ) : self.my_member = arg_my_member | Declaring members only in constructor |
Python | How would I use a Contextmanager for instance variables ? E.g.Let 's assume I 've got some Connection class , that must be closed on destruction . If I were to implement it as a ContextManager I could do.and it would get automatically closed on destruction . But what if I wanted to use it in a __init__ of another class... | with Connection ( ) as c : c.write ( 'FOO ' ) c.ask ( 'BAR ? ' ) class Device ( object ) : def __init__ ( self ) : self.connection = Connection ( ) # Must be closed on destruction . | How to use contextmanagers for instance variables |
Python | I ca n't find bytearray method or similar in Raku doc as in Python . In Python , the bytearray defined as this : Return a new array of bytes . The bytearray class is a mutable sequence of integers in the range 0 < = x < 256 . It has most of the usual methods of mutable sequences , described in Mutable Sequence Types , ... | class bytearray ( [ source [ , encoding [ , errors ] ] ] ) | Does Perl 6 have an equivalent to Python 's bytearray method ? |
Python | I need help to match 2 strings and replace with empty string ' ' . Appreciate your help as i am still new in Python and coding : Will always have 27 lines starting with first lineSecond is : | crypto pki certificate chain TP-self-signed-1357590403 +30820330 30820218 A0030201 02020101 300D0609 2A864886 F70D0101 05050030 +31312F30 2D060355 04031326 494F532D 53656C66 2D536967 6E65642D 43657274 +69666963 6174652D 31333537 35393034 3033301E 170D3139 30313234 31353436 +34345A17 0D323030 31303130 30303030 305A3031 ... | Regex to match and replace string with multiple lines Python |
Python | I have 3 different DataFrames ( 1 master DataFrame and 2 additional DataFrames ) . I am trying to add a column to my master DataFrame , with the elements of the column being different cell values in the other two DataFrames . I am using two columns of the master DataFrame to figure out which of the 2 DataFrames I need ... | master_df = pd.DataFrame ( { 'col1 ' : [ 'M ' , ' F ' , ' F ' , 'M ' ] , 'col2 ' : [ 0 , 1 , 2 , 3 ] , 'col3 ' : [ ' X ' , ' Z ' , ' Z ' , ' X ' ] , 'col4 ' : [ 2021 , 2022 , 2023 , 2024 ] } ) df1 = pd.DataFrame ( { 2021 : [ .632 , .214 , .987 , .555 ] , 2022 : [ .602 , .232 , .287 , .552 ] , 2023 : [ .932 , .209 , .34... | How to efficiently get cell values from multiple DataFrames to insert into a master DataFrame |
Python | Problem description : I have a class C inheriting from mixins A and B.I want a new class , C_ , having all the methods/attributes defined in the class C but with B swapped with B_ ( same API ) in the inheritance scheme ( one possible use of this is easy mocking ) . All classes are new style classes.I got what I wanted ... | A B B_ B_ A B \ / / \ \ / C / \ C \ / \ / C1 C2C1 ( C , B_ ) C2 ( B_ , C ) C1.__mro__ = ( C1 , C , A , B , B_ , object ) C2.__mro__ = ( C2 , B_ , C , A , B , object ) | Is that OK to use the MRO in order to override a mixin ? |
Python | I have a list with strings called names , I need to search each element in the names list with each element from the pattern list . Found several guides that can loop through for a individual string but not for a list of strings Thank you in advance ! Desired output : | a = [ x for x in names if 'st ' in x ] names = [ 'chris ' , 'christopher ' , 'bob ' , 'bobby ' , 'kristina ' ] pattern = [ 'st ' , 'bb ' ] a = [ 'christopher ' , 'bobby ' , 'kristina ] | Search list of string elements that match another list of string elements |
Python | When I run ionic start helloWorld blank , I receive the following error : The above command worked without error when I tried it last ( a few months ago ) . Now I 've tried updating ionic , but still same error.I had recently used Anaconda to get python3 . So I 'm afraid this might be related to that . I tried an alias... | Error with start undefinedError Initializing app : There was an error with the spawned command : npminstall conda install python=2.7.3 Cordova CLI : 6.5.0 Ionic CLI Version : 2.2.3Ionic App Lib Version : 2.2.1ios-deploy version : 1.9.0 ios-sim version : 5.0.8 OS : macOSNode Version : v9.4.0Xcode version : Xcode 9.4.1 B... | Ionic `` Error with start undefined '' after python3 |
Python | Situation : We know that the below will check if the script has been called directly.Problem : The else clause is only a generic one and will run as long as the script was not called directly.Question : Is there any way to get which file it was imported in , if it is not called directly ? Additional information : Below... | if __name__ == '__main__ ' : print `` Called directly '' else : print `` Imported by other python files '' if __name__ == '__main__ ' : print `` Called directly '' elif < something > == `` fileA.py '' : print `` Called from fileA.py '' elif < something > == `` fileB.py '' : print `` Called from fileB.py '' else : print... | How to find which file was the `` initiator '' Python |
Python | I inadvertently ran across a phenomenon that has me a bit perplexed . I was using IDLE for some quick testing , and I had some very simple code like this ( which I have simplified for the purpose of illustration ) : Now I ran this code like so ( several times , with the same basic results ) : My first hunch was that pe... | from time import clock # I am presently using windowsdef test_speedup ( ) : c = clock ( ) for i in range ( 1000 ) : print i , print '= > ' , clock ( ) - c # without pressing enter > > > test_speedup ( ) 0 1 2 3 4 . . . 997 998 999 = > 12.8300956124 # the time to run code in seconds # pressing enter ONLY 3 TIMES while t... | Why does periodically pressing the enter key substantially speed up my code ? |
Python | Due to some restrictions in a project I 'm working on , I had to replace Django 's QuerySet class with a custom one.QuerySet objects can have their methods chained ( eg QuerySet ( ) .filter ( ... ) .exclude ( ... ) and so on ) , so in my implementation , every method simply returns self . So my class looks like this : ... | class MyQuerySet : ... def filter ( self , *args , **kwargs ) : # Do some stuff and then : return self class QuerySet ( ... ) : ... def filter ( self , *args , **kwargs ) : clone = self._clone ( ) # Do some stuff and then return clone def _clone ( self , ... ) : klass = self.__class__ obj = klass ( ... ) return obj | Python - Chaining methods : returning ` self ` vs returning a new cloned object |
Python | The sqlalchemy core query builder appears to unnest and relocate CTE queries to the `` top '' of the compiled sql.I 'm converting an existing Postgres query that selects deeply joined data as a single JSON object . The syntax is pretty contrived but it significantly reduces network overhead for large queries . The goal... | with res_cte as ( select account_0.name acct_name , ( with offer_cte as ( select offer_0.id from offer offer_0 where offer_0.account_id = account_0.id ) select array_agg ( offer_cte.id ) from offer_cte ) as offer_arr from account account_0 ) select acct_name : :text , offer_arr : :textfrom res_cte acct_name , offer_arr... | SQLAlchemy Nested CTE Query |
Python | I am trying to create a game using livewires in which there are multiple levels . In each level , the screen will need to be a different size , so either I can create a new screen , or I can resize it . When I tried a new screen , like this ( mcve ) : I get the error : games.screen.width and height can not be set ( you... | from livewires import gamesgames.init ( screen_width = 500 , screen_height=100 , fps = 50 ) # dosomethinggames.screen.quit ( ) games.init ( screen_width = 100 , screen_height=500 , fps = 50 ) games.screen.mainloop ( ) Traceback ( most recent call last ) : File `` C : \Users\Fred\Desktop\game\main.py '' , line 6 , in < ... | Python livewires resize screen |
Python | In Python , varargs collection seems to work quite differently from how sequence unpacking works in assignment statements . I 'm trying to understand the reason for this potentially confusing difference . I 'm sure there is a good reason , but what is it ? The function call results in the following error : Question 1 :... | # Example 1 with assignment statementa , *b , c = 1,2,3,4print ( b ) # [ 2 , 3 ] # Example 1 with function calldef foo ( a , *b , c ) : print ( b ) foo ( 1,2,3,4 ) Traceback ( most recent call last ) : File `` < pyshell # 309 > '' , line 1 , in < module > foo ( 1,2,3,4 ) TypeError : foo ( ) missing 1 required keyword-o... | Why does * work differently in assignment statements versus function calls ? |
Python | In numpy I would like to make a 2d arrray ( r , by 2**r ) where the columns are all possible binary columns . For example , if height of the columns is 5 , the columns would be My solution isThis seems very ugly . Is there a more elegant way ? | [ 0,0,0,0,0 ] , [ 0,0,0,0,1 ] , [ 0,0,0,1,0 ] , [ 0,0,0,1,1 ] , [ 0,0,1,0,0 ] , ... np.array ( list ( itertools.product ( [ 0,1 ] , repeat = c ) ) ) .T | An elegant way to make a 2d array with all possible columns |
Python | Today , I used math.log ( ) function to get the logarithm of 4913 to the given base 17 . The answer is 3 , but when I ran the code below , I got 2.9999999999999996.1 ) Is it because math.log ( x , b ) 's calculation is log ( x ) / log ( b ) ? 2 ) Is there any solution to get the correct answer 3 ? | import mathprint ( math.log ( 4913,17 ) ) | Wrong answer from math.log ( python 3 ) |
Python | Why does this return 3 instead of 6 , if bool ( i ) returns True for all values i not equal to 0 ? | [ 1 , 1 , 1 , 2 , 2 , 3 ] .count ( True ) > > > 3 | Integer to boolean conversion in count ( ) method |
Python | I have a Gtk.TreeView here . Most but not all of the items should be able to be dragged & dropped . In this example the first item should not be able to be dragged & dropped but it should be selectable.How can I realize this ? Maybe I have to use the drag-begin signal and stop the drag in there . But I do n't know how ... | # ! /usr/bin/env python3import gigi.require_version ( 'Gtk ' , ' 3.0 ' ) from gi.repository import Gtkfrom gi.repository import Gdkclass MainWindow ( Gtk.Window ) : def __init__ ( self ) : Gtk.Window.__init__ ( self , title= '' TreeView Drag and Drop '' ) self.connect ( `` delete-event '' , Gtk.main_quit ) self.set_def... | Cancel a Drag & Drop for some specific items in a Gtk.TreeView |
Python | I am trying to add a tuple of a ( number , ( tuple ) ) , but it drops the outer tuple.How do I change the code so that l1 comes out looking like L2 ? It appears to drop the outer tuple and convert it to list elements ? How do I stop that ? Better yet , why is it happening ? l1 comes out as [ 1.0 , ( 2.0 , 3.0 ) , 4.0 ,... | l1 = [ ] t1 = ( 1.0 , ( 2.0,3.0 ) ) l1.extend ( ( t1 ) ) t2 = ( 4.0 , ( 5.0,6.0 ) ) l1.extend ( t2 ) print ( l1 ) l2 = [ ( 1.0 , ( 2.0,3.0 ) ) , ( 4.0 , ( 5.0,6.0 ) ) ] print ( l2 ) | Add number , then tuple to list as a tuple , but it drops outer tuple |
Python | I 'm using xmltodict to parse an XML config . The XML has structures where an element can occur in 1 to n instances , where both are valid : and I 'm parsing this with xmltodict as follows : and it gives back a single unicode or a list ( depending the items found ) , so I always need to add an extra check to ensure if ... | < items > < item-ref > abc < /item-ref > < /items > < items > < item-ref > abc < /item-ref > < item-ref > dca < /item-ref > < item-ref > abb < /item-ref > < /items > document [ 'items ' ] [ 'item-ref ' ] if isinstance ( document [ 'items ' ] [ 'item-ref ' ] , list ) : my_var = document [ 'items ' ] [ 'item-ref ' ] else... | Handle 1 to n elements |
Python | What is the most reliable way for adding pretty-printing support to custom python3 classes ? For interactive data evaluation I found pretty-printing support quite important . However , both iPython 's pretty-printer IPython.lib.pretty.pprint and the standard-library pprint.pprint support only builtin structure types by... | class MyPrettyClass ( dict ) : def __init__ ( self , ... ) : self.__dict__ = self self._class = self.__class__ # In order to recognize the type . ... < A LOT OF FIELDS > ... { '__lp_mockup_xml ' : < lxml.etree._ElementTree object at 0x0000021C5EB53DC8 > , '__lp_mockup_xml_file ' : ' E : \\DataDirectory\\mockup.xml ' , ... | How to support pretty-printing in custom python 3 classes ? |
Python | I 'm puzzled by this behaviour of memory allocation of sets : Why using a set as argument doubles the amount of memory used by the resulting set ? The result in both cases is identical to the original set : Note that the same happens using a normal iterator : And with the update method : At first I thought that it was ... | > > > set ( range ( 1000 ) ) .__sizeof__ ( ) 32968 > > > set ( range ( 1000 ) ) .union ( range ( 1000 ) ) .__sizeof__ ( ) # expected , set does n't change32968 > > > set ( range ( 1000 ) ) .union ( list ( range ( 1000 ) ) ) .__sizeof__ ( ) # expected , set does n't change32968 > > > set ( range ( 1000 ) ) .union ( set ... | Why does union consume more memory if the argument is a set ? |
Python | I use pytest in my .travis.yml to check my code.I would like to check the README.rst , too.I found readme_renderer via this StackO answerNow I ask myself how to integrate this into my current tests.The docs of readme_renderer suggest this , but I have not clue how to integrate this into my setup : | python setup.py check -r -s | How to integrate checking of readme in pytest |
Python | Is there a way to take ... ... and turn it into ... I was able to do it with np.apply_along_axis ... and with for loops ... but they are too slow . Is there a faster way ? Thanks in advance . | > > > x = np.array ( [ 0 , 8 , 10 , 15 , 50 ] ) .reshape ( ( -1 , 1 ) ) ; ncols = 5 array ( [ [ 0 , 1 , 2 , 3 , 4 ] , [ 8 , 9 , 10 , 11 , 12 ] , [ 10 , 11 , 12 , 13 , 14 ] , [ 15 , 16 , 17 , 18 , 19 ] , [ 50 , 51 , 52 , 53 , 54 ] ] ) > > > def myFunc ( a , ncols ) : return np.arange ( a , ( a+ncols ) ) > > > np.apply_a... | Numpy : Array of ` arange ` s |
Python | If I do this : Is ' a ' destroyed immediately after leaving foo ? Or does it wait for some GC to happen ? | def foo ( ) : a = SomeObject ( ) | Are there stack based variables in Python ? |
Python | I have a list of lists as follows.I want to get the count of each word in the sentences list . So , my output should look as follows.I am currently doing it as follows.However , it is not efficient at all for long lists . I have a really long list with about 1 million sentences in the list . It took me two days to run ... | sentences = [ [ `` my '' , `` first '' , `` question '' , `` in '' , `` stackoverflow '' , `` is '' , `` my '' , `` favorite '' ] , [ `` my '' , `` favorite '' , `` language '' , `` is '' , `` python '' ] ] { 'stackoverflow ' : 1 , 'question ' : 1 , 'is ' : 2 , 'language ' : 1 , 'first ' : 1 , 'in ' : 1 , 'favorite ' :... | Count strings in nested list |
Python | I want to connect EC2 using pysftp library via AWS Lambda . I use below code to connect.I have put .pem file along with deployment package in AWS Lambda . See this image : Sometimes it works sometime not , like sometimes it says .pem file not found.How to deal with it ? Is there any way to access .pem file or data of .... | mysftp = pysftp.Connection ( host=Constants.MY_HOST_NAME , username=Constants.MY_EC2_INSTANCE_USERNAME , private_key= '' ./clientiot.pem '' , cnopts=cnopts , ) `` [ Errno 2 ] No such file or directory : './clientiot.pem ' '' | How to connect EC2 using pysftp via AWS Lambda without .pem file or alternate to .pem file |
Python | Is there any way to write both commands and their output to an external file ? Let 's say I have a script outtest.py : Now if I want to capture its output only I know I can just do : However , this will only give me an outtest.txt file with e.g . : What I 'm looking for is a way to get an output file like : Or some oth... | import randomfrom statistics import median , meand = [ random.random ( ) **2 for _ in range ( 1000 ) ] d_mean = round ( mean ( d ) , 2 ) print ( f'mean : { d_mean } ' ) d_median = round ( median ( d ) , 2 ) print ( f'median : { d_median } ' ) python3 outtest.py > outtest.txt mean : 0.34median : 0.27 import randomfrom s... | Python write both commands and their output to a file |
Python | I have two numpy arraysand I want to generate array C : I have tried some ways.. but they seem very inefficient . Is there any way this can be done efficiently ? | A= array ( [ [ 1,2,3,4 ] , [ 5,6,7,8 ] , [ 9,10,11,12 ] ] ) B = array ( [ 10,20,30 ] ) C = array ( [ 11,12,13,14 ] , [ 25,26,27,28 ] , [ 39,40,41,42 ] ] ) | Adding value of single numpy array to all columns in other numpy array |
Python | This is more of an 'interesting ' phenomena I encountered in a Python module that I 'm trying to understand , rather than a request for help ( though a solution would also be useful ) .Yeah , so the fuzzy module totally violates the immutability of strings in Python . Is it able to do this because it is a C-extension ?... | > > > import fuzzy > > > s = fuzzy.Soundex ( 4 ) > > > a = `` apple '' > > > b = a > > > sdx_a = s ( a ) > > > sdx_a'A140 ' > > > a'APPLE ' > > > b'APPLE ' | String immutability in CPython violated |
Python | One of the answers to this question isif the length of s > 5 , then ' y ' is printed otherwise ' n ' is . Please explain how/why this works . Thanks.I understand that this is not a recommended approach but I 'd like to understand why it works . | print len ( s ) > 5 and ' y ' or ' n'print ( len ( s ) > 5 and ' y ' or ' n ' ) # python3 | why is the construct x = ( Condition and A or B ) used ? |
Python | Why does pandas behave differently when setting or getting items in a series with erroneous number of indexes : Edit : Reported . | df = pd.DataFrame ( { ' a ' : [ 10 ] } ) # df [ ' a ' ] is a series , can be indexed with 1 index only # will raise IndexingError , as expecteddf [ ' a ' ] .iloc [ 0 , 0 ] df [ ' a ' ] .loc [ 0 , 0 ] # will raise nothing , not as expecteddf [ ' a ' ] .iloc [ 0 , 0 ] = 1000 # equivalent to passdf [ ' a ' ] .loc [ 0 , 0 ... | Why pandas silently ignores .iloc [ i , j ] assignment with too many indices ? |
Python | I am using pygraphviz to create a large number of graphs for different configurations of data . I have found that no matter what information is put in the graph the program will crash after drawing the 170th graph . There are no error messages generated the program just stops . Is there something that needs to be reset... | for graph_number in range ( 200 ) : config_graph = pygraphviz.AGraph ( strict=False , directed=False , compound=True , ranksep= ' 0.2 ' , nodesep= ' 0.2 ' ) # Create Directory if not os.path.exists ( 'Graph ' ) : os.makedirs ( 'Graph ' ) # Draw Graph print ( 'draw_ ' + str ( graph_number ) ) config_graph.layout ( prog ... | Pygraphviz crashes after drawing 170 graphs |
Python | I 'm trying to scrape an xml file with BeautifulSoup 4.4.0 that has tag names in camelCase and find_all does n't seem to be able to find them . Example code : The output I get is : What 's the correct way to look up camel cased/uppercased tag names ? | from bs4 import BeautifulSoupxml = `` '' '' < hello > world < /hello > '' '' '' soup = BeautifulSoup ( xml , `` lxml '' ) for x in soup.find_all ( `` hello '' ) : print xxml2 = `` '' '' < helloWorld > : - ) < /helloWorld > '' '' '' soup = BeautifulSoup ( xml2 , `` lxml '' ) for x in soup.find_all ( `` helloWorld '' ) :... | find_all with camelCase tag names with BeautifulSoup 4 |
Python | I need to derive all the combinations out of it as below.and so on . There could be any level of nesting herePlease let me know how to achieve thisSomething that I tried is pasted below but definitely was reaching nowhere Which resulted in | my_dict = { ' a ' : [ 1,2 ] , ' b ' : [ 3 ] , ' c ' : { 'd ' : [ 4,5 ] , ' e ' : [ 6,7 ] } } { ' a':1 , ' b':3 , ' c ' : { 'd':4 , ' e':6 } } { ' a':1 , ' b':3 , ' c ' : { 'd':4 , ' e':7 } } { ' a':1 , ' b':3 , ' c ' : { 'd':5 , ' e':6 } } { ' a':1 , ' b':3 , ' c ' : { 'd':5 , ' e':7 } } { ' a':2 , ' b':3 , ' c ' : { '... | Split python dictionary to result in all combinations of values |
Python | In my model.py , i have define a class : In url.py ( Project url ) In url.py ( app url ) In index.htmlWhile reloading , it gives | def get_absolute_url ( self ) : return reverse ( `` posts : detail '' , kwargs= { `` id '' : self.id } ) urlpatterns = [ url ( r'^admin/ ' , admin.site.urls ) , url ( r'^posts/ ' , include ( `` posts.urls '' , namespace='posts ' ) ) , ] urlpatterns = [ url ( r'^ $ ' , post_list ) , url ( r'^create/ $ ' , post_create ) ... | NoReverseMatch at /posts/ while using absolute url in django |
Python | Say I have the following dataframe : As can be seen I am starting column D with 100 at the last row.I am trying to code a calculation for column D so starting from the bottom row ( row 19 ) when a BUY or SELL is shown on column B then the number on column D is locked ( eg the 100 ) and used for a calculation based on c... | import pandas as pddf = pd.DataFrame ( ) df [ ' A ' ] = ( ' 1/05/2019 ' , ' 2/05/2019 ' , ' 3/05/2019 ' , ' 4/05/2019 ' , ' 5/05/2019 ' , ' 6/05/2019 ' , ' 7/05/2019 ' , ' 8/05/2019 ' , ' 9/05/2019 ' , '10/05/2019 ' , '11/05/2019 ' , '12/05/2019 ' , '13/05/2019 ' , '14/05/2019 ' , '15/05/2019 ' , '16/05/2019 ' , '17/05... | Dataframe cell to be locked and used for a running balance calculation conditional of result on another cell on same row |
Python | First I build a new DataFrame frame . Then create a new frame2 by filtering some data from frame . Now I want to assign some value to frame2 : but I got this warning : why I keep got this warning although I used the recommended .loc syntax ? what i supposed to do to avoid this warning ? | import numpy as npfrom pandas import DataFrameframe = DataFrame ( np.arange ( 9 ) .reshape ( ( 3 , 3 ) ) , index= [ ' a ' , ' c ' , 'd ' ] , columns= [ 'Ohio ' , 'Texas ' , 'California ' ] ) mask = frame [ 'Texas ' ] > 1print frame [ mask ] frame2 = frame.loc [ mask ] frame2.loc [ ' c ' , 'Ohio ' ] = 'me'print frame2 C... | pandas SettingWithCopyWarning after trying .loc |
Python | BackgroundI have two numpy arrays which I 'd like to use to carry out some comparison operations in the most efficient/fast way possible . Both contain only unsigned ints . pairs is a n x 2 x 3 array , which holds a long list of paired 3D coordinates ( for some nomenclature , the pairs array contains a set of pairs ...... | # full pairs arrayIn [ 145 ] : pairsOut [ 145 ] : array ( [ [ [ 1 , 2 , 4 ] , [ 3 , 4 , 4 ] ] , ... .. [ [ 1 , 2 , 5 ] , [ 5 , 6 , 5 ] ] ] ) # each entry contains a pair of 3D coordinatesIn [ 149 ] : pairs [ 0 ] Out [ 149 ] : array ( [ [ 1 , 2 , 4 ] , [ 3 , 4 , 4 ] ] ) In [ 162 ] : positionsOut [ 162 ] : array ( [ [ 1 ... | Efficient Python implementation of numpy array comparisons |
Python | I have a function that must never be called with the same value simultaneously from two threads . To enforce this , I have a defaultdict that spawns new threading.Locks for a given key . Thus , my code looks similar to this : The problem is that I can not figure out how to safely delete the lock from the defaultdict on... | from collections import defaultdictimport threadinglock_dict = defaultdict ( threading.Lock ) def f ( x ) : with lock_dict [ x ] : print `` Locked for value x '' | Garbage-collect a lock once no threads are asking for it |
Python | If I try to compile a function , containing an array of conditions , with numba 's jit-compiler , it takes very long . The program looks essentially likewhere I have excluded everything that will not alter the compilation time significantly . The problem arises if I use more than 20 elements . Despite that , the functi... | from numba import jitimport numpy as np @ jit ( nopython=True ) def foo ( a , b ) : valid = [ ( a - 1 > = 0 ) and ( b - 1 > = 0 ) , ( a - 1 > = 0 ) and ( b - 1 > = 0 ) , ( a - 1 > = 0 ) and ( b - 1 > = 0 ) , ( a - 1 > = 0 ) and ( b - 1 > = 0 ) , ( a - 1 > = 0 ) and ( b - 1 > = 0 ) , ( a - 1 > = 0 ) and ( b - 1 > = 0 ) ... | The compilation of an array of conditions with numba.jit takes a long time |
Python | If I define the __iter__ method as follows , it wo n't work : Result : As you can see , calling A ( ) .__iter__ ( ) works , but A ( ) is not iterable.However if I define __iter__ for the class , then it will work : Does anyone know why python has been designed like this ? i.e . why __iter__ as instance variable does no... | class A : def __init__ ( self ) : self.__iter__ = lambda : iter ( 'text ' ) for i in A ( ) .__iter__ ( ) : print ( i ) iter ( A ( ) ) textTraceback ( most recent call last ) : File `` ... \mytest.py '' , line 10 , in < module > iter ( A ( ) ) TypeError : ' A ' object is not iterable class A : def __init__ ( self ) : se... | Why ` __iter__ ` does not work when defined as an instance variable ? |
Python | I have this dataframe : The operation consists of grouping by column 'entity ' doing a count operation based on a two logical conditions applied to a column 'value ' and column 'type ' . In my case , I have to count the values greater than 3 in the column 'name ' and are not equal to 'medium ' in the column 'type ' . T... | df = pd.DataFrame ( { 'value ' : [ 1,2,3,4,2,42,12,21,21,424,34,12,42 ] , 'type ' : [ 'big ' , 'small ' , 'medium ' , 'big ' , 'big ' , 'big ' , 'big ' , 'medium ' , 'small ' , 'small ' , 'small ' , 'medium ' , 'small ' ] , 'entity ' : [ ' R ' , ' R ' , ' R ' , ' P ' , ' R ' , ' P ' , ' P ' , ' P ' , ' R ' , ' R ' , ' ... | Groupby based on a multiple logical conditions applied to a different columns DataFrame |
Python | I have written the following code in Python , in order to estimate the value of Pi . It is called Monte Carlo method . Obviously by increasing the number of samples the code becomes slower and I assume that the slowest part of the code is in the sampling part . How can I make it faster ? Do you suggest other ( presumab... | from __future__ import divisionimport numpy as npa = 1n = 1000000s1 = np.random.uniform ( 0 , a , n ) s2 = np.random.uniform ( 0 , a , n ) ii=0jj=0for item in range ( n ) : if ( ( s1 [ item ] ) **2 + ( s2 [ item ] ) **2 ) < 1 : ii = ii + 1print float ( ii*4/ ( n ) ) | How to increase the performance for estimating ` Pi ` in Python |
Python | Can I place : inside __init__.py on the top level dir on my package and garantee that the absolute_import will be applied to all code that runs inside that package or sub-packages ? Or should I put that directive in each model that does an absolute import ? I maintain a Python package and I 'm trying to keep my code as... | from __future__ import absolute_import | How to force my whole package to use a __future__ directive ? |
Python | Pylint is yelling at me for putting a from .views import *at the end of my __init__.pysaying imports should be placed at the top of the module.If I place it at the top of __init__.py then Flask ca n't find my routes ( views ) so that does n't work . Page does n't load , 404 error . Loads fine when routes are imported a... | .├── README.md├── my_app│ ├── __init__.py│ ├── forms.py│ ├── models.py│ ├── static│ ├── templates│ │ ├── index.html│ │ └── loggedin.html│ └── views.py├── config.py├── instance│ └── config.py├── requirements.txt└── run.py from flask import Flask , render_templatefrom authlib.integrations.flask_client import OAuthapp = F... | Is a Python module import at the bottom ok ? |
Python | While cythonizing some PyQt5 code , I was encountering TypeError : method ( ) takes exactly 1 positional argument ( 2 given ) .Strangely , replacing PyQt5 with PySide2 seems to not cause this behavior . I was hoping someone could help me understand why this is happening.NOTE : running directly from source does not caus... | root/|- main.py|- setup.py|- lib/ |- __init__.py |- test.py import osimport tempfileimport shutilfrom distutils.core import setupfrom Cython.Build.Dependencies import cythonizefrom multiprocessing import pooldef run_distutils ( args ) : base_dir , ext_modules = args script_args = [ 'build_ext ' , '-i ' ] cwd = os.getcw... | Understanding inconsistent cythonized code behavior - PyQt5 vs. PySide2 |
Python | I have a function with several helper functions . That 's fairly common case . I want to group them in a common context for readability and I 'm wondering how to do it right.they take ~15 linesonly the main function is called from somewhere elseno plans on reusing the helper functions in the near futureSimplified examp... | def create_filled_template_in_temp ( path , values_mapping ) : template_text = path.read_text ( ) filled_template = _fill_template ( template_text , values_mapping ) result_path = _save_in_temp ( filled_template ) return result_pathdef _fill_template ( template_text , values_mapping ) : ... def _save_in_temp ( filled_t... | How to group functions without side effects ? |
Python | While investigating this question , I came across this strange behavior of single-argument super : Calling super ( some_class ) .__init__ ( ) works inside of a method of some_class ( or a subclass thereof ) , but throws an exception when called anywhere else.Code sample : The exception being thrown isI do n't understan... | class A ( ) : def __init__ ( self ) : super ( A ) .__init__ ( ) # does n't throw exceptiona = A ( ) super ( A ) .__init__ ( ) # throws exception Traceback ( most recent call last ) : File `` untitled.py '' , line 8 , in < module > super ( A ) .__init__ ( ) # throws exceptionRuntimeError : super ( ) : no arguments | Does any magic happen when I call ` super ( some_cls ) ` ? |
Python | I have used defer.inlineCallbacks in my code as I find it much easier to read and debug than using addCallbacks.I am using PB and I have hit a problem when returning data to the client . The data is about 18Mb in size and I get a failed BananaError because of the length of the string being returned.What I want to do is... | @ defer.inlineCallbacksdef getLatestVersions ( self ) : returnlist = [ ] try : latest_versions = yield self.cur.runQuery ( `` '' '' SELECT id , filename , path , attributes , MAX ( version ) , deleted , snapshot , modified , size , hash , chunk_table , added , isDir , isSymlink , enchash from files group by filename , ... | Twisted inlineCallbacks and remote generators |
Python | I 'm sure there is a really simple answer to this but I ca n't find it after searching around for a while.The above code works perfectly , the condition on the if statement seems a bit long-winded so I tried : which is shorter but does n't work . I worked out that it does n't work because `` O '' is a boolean expressio... | prefixes = `` JKLMNOPQ '' suffix = `` ack '' for letter in prefixes : if letter == `` Q '' or letter == `` O '' : print letter + `` u '' + suffix else : print letter + suffix if letter == `` Q '' or `` O '' : if letter == ( `` Q '' or `` O '' ) : | Using `` or '' in if statement conditions |
Python | How does evaluating + 5 work ( spoiler alert : result is 5 ) ? Is n't the + working by calling the __add__ method on something ? 5 would be `` other '' in : So what is the `` void '' that allows adding 5 ? void.__add__ ( 5 ) Another clue is that : throws the error : | > > > other = 5 > > > x = 1 > > > x.__add__ ( other ) 6 / 5 TypeError : 'int ' object is not callable | How is it possible to evaluate +5 in Python ? |
Python | I want to create a nested JSON based on this CSV File ( it 's only a snippet ) In this formThis is my codeAs you can see all countries except one country do n't get the data from the csv . Where is the mistake . How can I export the json ? I 'm actually copying the printed into my text Editor | Datum , Position , Herkunft , Entscheidungen insgesamt , Insgesamt_monat , Asylberechtigt , Asylberechtigt monat , Asylberechtigt Prozent , Flüchtling , Flüchtling monat , Flüchting Prozent , Gewährung von subisdiärem Schutz , Gewährung monat , Prozent , Abschiebungsverbot , Abschiebungsverbot monat , Prozent , Unbegre... | Nested JSON from CSV |
Python | Apologies for the vague question name , but I 'm not really sure how to call this operation.I have the following data frame : This data represents a `` ranking '' of each of the options , A , B and C for each row . So , for example , in row 2 , C was the best , then A , then B. I would like to construct the `` inverted... | import pandas as pddf = pd.DataFrame ( { ' A ' : [ 1 , 3 , 2 , 1 , 2 ] , ' B ' : [ 2 , 1 , 3 , 2 , 3 ] , ' C ' : [ 3 , 2 , 1 , 3 , 1 ] , } ) print ( df ) # A B C # 0 1 2 3 # 1 3 1 2 # 2 2 3 1 # 3 1 2 3 # 4 2 3 1 out = pd.DataFrame ( { 1 : [ ' A ' , ' B ' , ' C ' , ' A ' , ' C ' ] , 2 : [ ' B ' , ' C ' , ' A ' , ' B ' ,... | Turning values into columns |
Python | I was staring at a piece of Python code I produced , which , though correct , is ugly . Is there a more pythonic way of doing this ? The problem is the repetition of the method calls for get_pixel and set_pixel . For your information : Also note that I 'd like to preserve code clarity and cleanness . | r = self.get_pixel ( x , y , RED ) g = self.get_pixel ( x , y , GREEN ) b = self.get_pixel ( x , y , BLUE ) t = function ( r , g , b ) if t : r2 , g2 , b2 = t self.set_pixel ( x , y , RED , r2 ) self.set_pixel ( x , y , GREEN , g2 ) self.set_pixel ( x , y , BLUE , b2 ) RED , GREEN , BLUE = range ( 3 ) | Pythonic way of repeating a method call on different finite arguments |
Python | It looks like , for Cython 's cdef-classes , using class special methods is sometimes faster than identical `` usual '' method , for example __setitem__ is 3 times faster than setitem : and now : This neither the `` normal '' behavior for Python , for which the special functions are even somewhat slower ( and obviosly ... | % % cythoncdef class CyA : def __setitem__ ( self , index , val ) : pass def setitem ( self , index , val ) : pass cy_a=CyA ( ) % timeit cy_a [ 0 ] =3 # 32.4 ns ± 0.195 ns per loop ( mean ± std . dev . of 7 runs , 10000000 loops each ) % timeit cy_a.setitem ( 0,3 ) # 97.5 ns ± 0.389 ns per loop ( mean ± std . dev . of ... | Why is __setitem__ much faster than an equivalent `` normal '' method for cdef-classes ? |
Python | There are 2 files named compare 1.txt and compare2.txt having random numbers in non-sequential ordercat compare1.txtcat compare2.txtAimOutput list of all the numbers which are present in compare1 but not in compare 2 and vice versaIf any number has zero in its prefix , ignore zeros while comparing ( basically the absol... | 571113388901491 0038891314571290 90911211 grep -Fxv -f compare1.txt compare2.txt & & grep -Fxv -f compare2.txt compare1.txt cat compare1.txt compare2.txt | sort |uniq | How to compare 2 files having random numbers in non sequential order ? |
Python | I want to split the contents of a CSS file into code blocks and push each block of code into a list using Python 3.5.So , given this CSS : We can clearly tell that it has multiple styles and / or types of indentation meaning the CSS has to be tidied to get this : How can I use Python to read a tidied string of CSS and ... | h1 { color : # 333 , background-color : transparent } h2 { font-weight:300 } h3 { font-weight : 200 } h1 { color : # 333 , background-color : transparent ; } h2 { font-weight : 300 ; } h3 { font-weight : 200 ; } styles = [ `` h1 { \n color : # 333 , background-color : transparent ; \n } '' , `` h2 { \n font-weight : 30... | How can I split code-blocks into a list ? |
Python | I have a dataframe and 2 separate dictionaries . Both dictionaries have the same keys but have different values . dict_1 has key-value pairs where the values are unique ids that correspond with the dataframe df . I want to be able to use the 2 dictionaries and the unique ids from the dict_1 to append the values of dict... | col_1 col_2 id col_3 100 500 a1 478 785 400 a1 490 ... ... a1 ... ... ... a2 ... ... ... a2 ... ... ... a2 ... ... ... a3 ... ... ... a3 ... ... ... a3 ... ... ... a4 ... ... ... a4 ... ... ... a4 ... 1 : [ 'a1 ' , 'a3 ' ] ,2 : [ 'a2 ' , 'a4 ' ] ,3 : [ ... ] ,4 : [ ... ] ,5 : [ ... ] , . 1 : [ 0 , 1 ] ,2 : [ 1 , 1 ] ,3... | Use dictionary data to append data to pandas dataframe |
Python | I 've made a classproperty descriptor and whenever I use a function decorated with it , I get multiple pylint inspection errors.Here is a sample class with a sample decorated function : Thanks to the descriptor , I can call Bar.foo and get the string foo returned.Unfortunately , whenever I use functions like this with ... | class Bar : `` '' '' Bar documentation. `` '' '' # pylint : disable=no-method-argument @ classproperty def foo ( ) : `` '' '' Retrieve foo. `` '' '' return `` foo '' class Bar : `` '' '' Bar documentation. `` '' '' # pylint : disable=no-method-argument @ classproperty def foo ( ) : `` '' '' Retrieve an object. `` '' ''... | How to disable pylint inspections for anything that uses my function ? |
Python | The following code prints a warning , as expected : However , when using eval , the warning message does not appear : Why do warnings behave differently in these two situations ? | > > > import warnings > > > def f ( ) : ... warnings.warn ( 'Deprecated ' , DeprecationWarning ) ... print ( 'In function f ( ) ' ) ... > > > f ( ) __main__:2 : DeprecationWarning : DeprecatedIn function f ( ) > > > eval ( ' f ( ) ' ) In function f ( ) | In Python , why do warnings not appear when using ` eval ` ? |
Python | I 've implemented a genetic algorithm trained neural network with a mutation operator like so : And chromosomes are initialized randomly initially : When performing crossover , offspring chromosomes can only ever have genes within the interval [ -1 , 1 ] because parent chromosomes also only have genes in that interval ... | def mutation ( chromosome , mutation_rate ) : for gene in chromosome : if random.uniform ( 0.00 , 1.00 ) < = mutation_rate : gene = random.uniform ( -1.00 , 1.00 ) def make_chromosome ( chromosome_length ) : chromosome = [ ] for _ in range ( chromosome_length ) : chromosome.append ( random.uniform ( -1.00 , 1.00 ) ) re... | How can a genetic algorithm optimize a neural network 's weights without knowing the search volume ? |
Python | Consider a pandas df with columns containing tuples of equal length.What 's the easiest way to unfold this vertically as follows ? : | L1 = [ [ 'ID1 ' , ( 'key1a ' , 'key1b ' , 'key1c ' ) , ( 'value1a ' , 'value1b ' , 'value1c ' ) ] , [ 'ID2 ' , ( 'key2a ' , 'key2b ' , 'key2c ' ) , ( 'value2a ' , 'value2b ' , 'value2c ' ) ] ] df1 = pd.DataFrame ( L1 , columns= [ 'ID ' , 'Key ' , 'Value ' ] ) > > > df1 ID Key Value0 ID1 ( key1a , key1b , key1c ) ( valu... | Pandas : Melting columns containing tuples |
Python | Consider the collection of floating-point numbers of the form 0.xx5 between 0.0 and 1.0 : [ 0.005 , 0.015 , 0.025 , 0.035 , ... , 0.985 , 0.995 ] I can make a list of all 100 such numbers easily in Python : Let 's look at the first few and last few values to check we did n't make any mistakes : Now I want to round each... | > > > values = [ n/1000 for n in range ( 5 , 1000 , 10 ) ] > > > values [ :8 ] [ 0.005 , 0.015 , 0.025 , 0.035 , 0.045 , 0.055 , 0.065 , 0.075 ] > > > values [ -8 : ] [ 0.925 , 0.935 , 0.945 , 0.955 , 0.965 , 0.975 , 0.985 , 0.995 ] > > > sum ( round ( value , 2 ) > value for value in values ) 50 > > > values = [ n/10*... | Explain a surprising parity in the rounding direction of apparent ties in the interval [ 0 , 1 ] |
Python | I need to create an object that would raise a custom exception , UnusableObjectError , when it is used in any way ( creating it should not create an exception though ) . I came up with the code below which seems to behave as expected . ( some improvements made , as suggested by Duncan in comments ) Questions : Is there... | a = UnusableClass ( ) # No errorb = UnusableClass ( ) # No errora == 4 # Raises UnusableObjectError ' x ' in a # Raises UnusableObjectErrorfor i in a : # Raises UnusableObjectError print ( i ) # ..and so on class UnusableObjectError ( Exception ) : passCLASSES_WITH_MAGIC_METHODS = ( str ( ) , object , float ( ) , dict ... | Object that raises exception when used in any way |
Python | Following the instructions on the PyCall.jl readme , I am tying to use a pipenv python when using PyCall for my julia project ( in it 's own environment ) . In a terminal , I have activated the python environment using pipenv shell , and then located the pathfile of the pipenv version of python . PyCall has already bee... | ERROR : InitError : Incompatible ` libpython ` detected. ` libpython ` for C : \Users\me\.virtualenvs\iap\Scripts\python.exe is : C : \Users\me\.virtualenvs\iap\Scripts\python37.dll ` libpython ` for C : \Users\me\.julia\conda\3\python.exe is : C : \Users\me\.julia\conda\3\python36.dllPyCall.jl only supports loading Py... | PyCall unable to use pipenv version of python InitError : Incompatible ` libpython ` detected |
Python | Consider this ( all commands run on an 64bit Arch Linux system ) : Perl ( v5.24.0 ) awk ( GNU Awk 4.1.3 ) R ( 3.3.1 ) bcPython 2 ( 2.7.12 ) Python 3 ( 3.5.2 ) So , Perl , gawk and R agree , as do bc and Pyhon 2 . Nevertheless , between the 6 tools tested , I got 4 different results . I understand that this has somethin... | $ perl -le 'print 10190150730169267102/1000 % 10 ' 6 $ awk 'BEGIN { print 10190150730169267102/1000 % 10 } ' 6 > ( 10190150730169267102/1000 ) % % 10 [ 1 ] 6 $ echo 10190150730169267102/1000 % 10 | bc7 > > > print ( 10190150730169267102/1000 % 10 ) 7 > > > print ( 10190150730169267102/1000 % 10 ) 8.0 | Why do 4 different languages give 4 different results here ? |
Python | I 'm looking at some Python numpy code , which contains lines like ( From what I hopefully correctly understand , 1. is equivalent to 1.0 ) .Is there any reason to do this over a = 1 and x *= -1 ? I can understand it if I 'm going to be dividing a and x by an integer later on , so that I do n't have to worry about forg... | a = 1 . # later on , ` a ` is multiplied by other floatsx *= -1 . | Advantage of using `` x *= -1 . '' over `` x *= -1 '' ? |
Python | I need to find the row indices of all rows in a numpy array that differ only by sign . For example if I have the array : I would want the output to be [ ( 0,2 ) , ( 1,4 ) ] I know how to find unique rows , numpy.unique , so my intuition was to append the array to the negation of itself , i.e . numpy.concatenate ( A , -... | > > > Aarray ( [ [ 0 , 1 , 2 ] , [ 3 , 4 , 5 ] , [ 0 , -1 , -2 ] , [ 9 , 5 , 6 ] , [ -3 , -4 , -5 ] ] ) | find pairs of rows in numpy array that differ only by sign |
Python | I 'm trying to create a process that can run jobs on a cron schedule of 0/5 8-17 * * 1-5 and here is my test code : But it is not stopping after 5pm . Please help if I 'm using the cron arguments incorrectly . | import argparsefrom apscheduler.schedulers.background import BackgroundSchedulerimport datetimeimport timecmdline_parser = argparse.ArgumentParser ( description='Testing ' ) cmdline_parser.add_argument ( ' -- interval ' , type=int , default=5 ) def task ( ) : now = datetime.datetime.now ( ) .strftime ( ' % Y- % m- % d ... | How to set hour range and minute interval using APScheduler |
Python | Let 's say I have the following pandas DataFrame : So , there are odd rows in the DataFrame for Bob , namely rows 3 , 4 , and 5 . These values are consistently # , not 12 . Row 1 shows that Bob should be 12 , not # . In this example , it 's straightforward to fix this with replace ( ) : However , this would n't work fo... | import pandas as pddata = [ [ 'Alex',10 ] , [ 'Bob',12 ] , [ 'Clarke',13 ] , [ 'Bob ' , ' # ' ] , [ 'Bob ' , ' # ' ] , [ 'Bob ' , ' # ' ] ] df = pd.DataFrame ( data , columns= [ 'Name ' , 'Age ' ] , dtype=float ) print ( df ) Name Age0 Alex 101 Bob 122 Clarke 133 Bob # 4 Bob # 5 Bob # df = df.replace ( `` # '' , 12 ) p... | How to replace certain rows by shared column values in pandas DataFrame ? |
Python | Is there a better way to do this ? I was thinking of using a function because I have a lot of these in my code , Was curious if there was a shorter comprehensible way to do it . | if a > 1 : a = 1if a < 0 : a = 0 | Pythonic way to limit ranges on a variable ? |
Python | I want to use IFileOperation to copy files from python code - It 's fast ( er than python ) You get a nice dialogDoes n't block PythonOn Windows 10 , Python 3.8 - does n't seem to exist.How can I reach IFileOperation ( Not the deprecated SHFileOperation API ) using ctypes ? | import ctypesctypes.windll.shell32.IFileOperation | How to use IFileOperation from ctypes |
Python | Lets assume I have one list and another tuple both of them are already sorted : What I would need is to add all the elements from B into A in such a way that A remains sorted.Solution I could come with was : assuming A of size m , and B of size n ; this solution would take O ( mxn ) in worst case , how can I make it pe... | A = [ 10 , 20 , 30 , 40 ] B = ( 20 , 60 , 81 , 90 ) for item in B : for i in range ( 0 , len ( A ) ) : if item > A [ i ] : i += 1 else : A.insert ( i , item ) | Better way for concatenating two sorted list of integers |
Python | 2 days ago I was first introduced to Python ( and programming in general ) . Today I 'm stuck . I 've spent hours trying to find an answer to what I suspect is a problem so trivial , nobody else has yet been stuck here : ) The boss wants me to manually clean up HUGE .xml files into something more human readable . I 'm ... | < IssueTracking > < Issue > < SequenceNum > 123 < /SequenceNum > < Subject > Subject of Ticket 123 < /Subject > < Description > Line 1 in Description field of Ticket 123.Line 2 in Description field of Ticket 123.Line 3 in Description field of Ticket 123. < /Description > < /Issue > < Issue > < SequenceNum > 124 < /Sequ... | Python - How to nest file read loops ? |
Python | I have a numpy array in Python which is n-by-n ( in the example is 3-by-3 ) and contains zero values in all the diagonal positions . e.gIs it possible to sort the array without modifying the diagonal positions so as to look like the one below ? Because all of the sorting functions will take into account the `` zeros ''... | array ( [ [ 0. , -0.65 , 1.3 , 0.56 ] , [ 0.45 , 0. , 0.54 , 43 ] , [ 0.5 , 0.12 , 0. , 7 ] [ 0.2 , 0.3 , 0.4 , 0 ] ] ) array ( [ [ 0. , 1.3 , 0.56 , -0.65 ] , [ 43 , 0. , 0.54 , 0.45 ] , [ 7 , 0.5 , 0. , 0.12 ] [ 0.4 , 0.3 , 0.2 , 0 ] ] ) | Sort array in Python without modifying specific element positions |
Python | If it were just checking whether letters in a test_string are also in a control_string , I would not have had this problem.I will simply use the code below.But I also face a rather convoluted task of discerning whether the overlapping letters in the control_string are in the same sequential order as those in test_strin... | if set ( test_string.lower ( ) ) < = set ( control_string.lower ( ) ) : return True test_string = 'Dih'control_string = 'Danish'Truetest_string = 'Tbl'control_string = 'Bottle'False for i in test_string.lower ( ) : for j in control_string.lower ( ) : if i==j : index_factor = control_string.index ( j ) | check if letters of a string are in sequential order in another string |
Python | Is there a way to store commands in Python ? For example , to store a bash command I can put : Is there a way to store a command , for example something like this : which will work in the Python command prompt whenever/wherever it is opened ? Thank you . | # in .bash_profilealias myproject= '' cd /path/to/my/project '' $ project 'store ' profile= '' from userprofile.models import Profile '' > > > profile | How can I permanently store commands in the Python REPL/prompt ? |
Python | The coderuns on both Python 2 and Python 3 , but prints different results . Is this change documented anywhere ? ( A pointer to a mailing list discussion would also be fine -- I ask this purely out of curiosity . ) | x = 3def f ( ) : exec ( `` x = 2 '' ) print ( x ) f ( ) | Variables declared in exec'ed code do n't become local in Python 3 – documentation ? |
Python | I have a a program where circles can bounce into one another . I followed the directions from here for rotating the vectors and scaling the magnitudes based on the collision angle : http : //www.vobarian.com/collisions/2dcollisions2.pdfI wrote this code in python ( the 0 index indicates the x coordinate ) : The problem... | norm_vect = [ ( object2.pos [ 0 ] - object1.pos [ 0 ] ) , ( object2.pos [ 1 ] - object1.pos [ 1 ] ) ] unit = sqrt ( ( norm_vect [ 0 ] **2 ) + ( norm_vect [ 1 ] **2 ) ) unit_vect = [ float ( norm_vect [ 0 ] ) / unit , float ( norm_vect [ 1 ] ) /unit ] tan_vect = [ -unit_vect [ 1 ] , unit_vect [ 0 ] ] vel1 = object1.velv... | I ca n't find what 's wrong with this circle bounce calculation in python |
Python | I was reading the __init__ method of the Counter class , and saw this : I was n't sure what it meant by descriptor , so I checked the python data model document and found this : In general , a descriptor is an object attribute with “ binding behavior ” , one whose attribute access has been overridden by methods in the ... | if not args : TypeError ( `` descriptor '__init__ ' of 'Counter ' object `` `` needs an argument '' ) | Why is the __init__ method of Counter referred to as a descriptor ? |
Python | I know this goes against the definition of random numbers , but still I require this for my project.For instance , I want to generate an array with 5 random elements in range ( 0 , 200 ) .Now , I want each of the elements to have a difference of at least 15 between them.So the random array should look something like th... | [ 15 , 45 , 99 , 132 , 199 ] np.random.uniform ( low=0 , high=200 , size=5 ) | How to generate random numbers with each random number having a difference of at least x with all other elements ? |
Python | I have : This works for the first iteration , but then I get an error for the next iteration : Is there something I 'm doing wrong ? | context = torch.tensor ( context , dtype=torch.long , device=self.device ) context = context.unsqueeze ( 0 ) generated = context with torch.no_grad ( ) : past_outputs = None for i in trange ( num_words ) : print ( i , num_words ) inputs = { `` input_ids '' : generated } outputs , past_outputs = self.model ( **inputs , ... | How to use the past with HuggingFace Transformers GPT-2 ? |
Python | Perhaps this is also something for Cross Validated , but I am interested in how to do it in Python.I have a Pandas DataFrame containing a dataset D of instances which all have some continuous value x. x is distributed in a certain way , say uniform , could be anything.I want to draw n samples from D for which x has a t... | import numpy as npimport pandas as pdimport numpy.random as rndfrom matplotlib import pyplot as pltfrom tqdm import tqdmn_target = 30000n_dataset = 100000x_target_distribution = rnd.normal ( size=n_target ) # In reality this would be x_target_distribution = my_dataset [ `` x '' ] .sample ( n_target , replace=True ) df ... | Pandas : Sampling from a DataFrame according to a target distribution |
Python | I want to exhaustively analyse subroutines for sorting small arrays and need a way to generate all uniquely ordered arrays of a particular length.In Python , that would be lists with non-negative integers as elements and preferably using smallest integers when possible . For example , N = 3 : [ 1,1,1 ] and [ 2,2,0 ] do... | [ [ 0,0,0 ] , [ 0,0,1 ] , [ 0,1,0 ] , [ 0,1,1 ] , [ 0,1,2 ] , [ 0,2,1 ] , [ 1,0,0 ] , [ 1,0,1 ] , [ 1,0,2 ] , [ 1,1,0 ] , [ 1,2,0 ] , [ 2,0,1 ] , [ 2,1,0 ] ] | Python : Generate all uniquely ordered lists of length N |
Python | Consider the array aI can create b which contains the permutation to sort each column.I can sort a with bThat was the primer to illustrate the output I 'm looking for . I want an array b that has the required permutation for sorting the corresponding column in a when also considering a lexsort with another array.I want... | np.random.seed ( [ 3,1415 ] ) a = np.random.randint ( 10 , size= ( 5 , 4 ) ) aarray ( [ [ 0 , 2 , 7 , 3 ] , [ 8 , 7 , 0 , 6 ] , [ 8 , 6 , 0 , 2 ] , [ 0 , 4 , 9 , 7 ] , [ 3 , 2 , 4 , 3 ] ] ) b = a.argsort ( 0 ) barray ( [ [ 0 , 0 , 1 , 2 ] , [ 3 , 4 , 2 , 0 ] , [ 4 , 3 , 4 , 4 ] , [ 1 , 2 , 0 , 1 ] , [ 2 , 1 , 3 , 3 ] ]... | Broadcast 1D array against 2D array for lexsort : Permutation for sorting each column independently when considering yet another vector |
Python | Answering this question , some others and I were actually wrong by considering that the following would work : Say one hasWhat is the reason behindwhile one hasor orIs it the degeneracy in term of dimensions which causes this . | test = [ [ [ 0 ] , 1 ] , [ [ 1 ] , 1 ] ] import numpy as npnptest = np.array ( test ) > > > nptest [ : ,0 ] == [ 1 ] array ( [ False , False ] , dtype=bool ) > > > nptest [ 0,0 ] == [ 1 ] , nptest [ 1,0 ] == [ 1 ] ( False , True ) > > > nptest== [ 1 ] array ( [ [ False , True ] , [ False , True ] ] , dtype=bool ) > > >... | What is going on behind this numpy selection behavior ? |
Python | I found a programming problem I was unable to solve . I have been given a set A of integers . For all numbers x in A , find the smallest positive integer y such that the digits of x*y are increasing or decreasing and the product x*y is the smallest possible . For example , if A= ( 363 , 726 , 1089 ) then n= ( 184573 , ... | 363 726 1089 1313 1452 1717 1798 1815 1919 2121 2156 2178 2189 2541 2626 28052904 2997 3131 3267 3297 3434 3630 3838 3993 4037 4092 4107 4191 4242 4257 43124334 4343 4356 4378 4407 4532 4646 4719 4747 4807 4949 5011 5055 5071 5082 51515214 5353 5423 5445 5454 5495 5610 5665 5731 5808 5819 5858 5951 5989 5994 61716248 6... | How to find smallest positive integers to make digits monotonic ? |
Python | I am trying to figure out how to count up to a certain integer ( as a range ) alternating between two different numbers like 2 and 3 . So that the output would be 2 5 7 10 12 15 etc.I started off trying to alter a simple while loop like the following to take two values : But it just ends up counting up to 100 by 5 . I ... | a = 0 while a < 100 : a = a + 2 + 3 print ( a , end= ' ' ) | Python 3 - Counting up with two different values |
Python | This is super , super slow for some reason.There are a total of 2000 results.Below is an example of a result document ( from Mongo ) . All other results are similar in length.The whole process takings about 15 seconds ... what the hell ? How can I speed it up ? : ) Edit : I realize that when I print the count in consol... | meta_map = { } results = db.meta.find ( { 'corpus_id ' : id , 'method ' : method } ) # this Mongo query only takes 3ms print results.explain ( ) # result is mongo queryset of 2000 documents count = 0 for r in results : count += 1 print count word = r.get ( 'word ' ) data = r.get ( 'data ' , { } ) if not meta_map.has_ke... | This takes a long time ... how do I speed this dictionary up ? ( python ) |
Python | I need to turn a two column Dataframe to a list grouped by one of the columns . I have done it successfully in pandas : But now I am trying to do the same thing in pySpark as follows : and I am getting the error : I have tried several commands but I simply can not get it right . And the spark dokumentation does not con... | expertsDF = expertsDF.groupby ( 'session ' , as_index=False ) .agg ( lambda x : x.tolist ( ) ) expertsDF = df.groupBy ( 'session ' ) .agg ( lambda x : x.collect ( ) ) all exprs should be Column session name1 a1 b2 v2 c session name1 [ a , b ... . ] 2 [ v , c ... . ] | turning pandas to pyspark expression |
Python | The data is here : The Python code , incorporating recent changes , is as follows . There is no attempt to loop through different boards as my intermediate attempt . This data is just produced by a search all query . which produces , as before , the correct dictionary where the scoring is correct but there are duplicat... | { 'took ' : 0 , 'timed_out ' : False , '_shards ' : { 'total ' : 5 , 'successful ' : 5 , 'skipped ' : 0 , 'failed ' : 0 } , 'hits ' : { 'total ' : 16 , 'max_score ' : 1.0 , 'hits ' : [ { '_index ' : 'matchpoints ' , '_type ' : 'score ' , '_id ' : '6PKYGGgBjpp4O0gQgUu5 ' , '_score ' : 1.0 , '_source ' : { 'board_number ... | making a calculation with the elements of an elasticsearch json object , of a contract bridge score , using Python |
Python | I want to calculate the least squares estimate for given data.There are a few ways to do this , one is to use numpy 's least squares : Where X is a matrix and y a vector of compatible dimension ( type float64 ) . Second way is to calculate the result directly using the formula : My problem : there are cases where the d... | import numpynp.linalg.lstsq ( X , y ) [ 0 ] import numpynumpy.linalg.inv ( X.T.dot ( X ) ) .dot ( X.T ) .dot ( y ) | Why does numpy least squares result diverge from using the direct formula ? |
Python | I have a list of sentences of a few topics ( two ) like the below : As you can see there is similarity in sentences.I am trying to relate multiple sentences and visualise the characteristics of them by using a graph ( directed ) . The graph is built from a similarity matrix , by applying row ordering of sentences as sh... | SentencesTrump says that it is useful to win the next presidential election . The Prime Minister suggests the name of the winner of the next presidential election.In yesterday 's conference , the Prime Minister said that it is very important to win the next presidential election . The Chinese Minister is in London to d... | Graph to connect sentences |
Python | I 've been learning the basics of Python for a short while , and thought I 'd go ahead and try to put something together , but appear to have hit a stumbling block ( despite looking just about everywhere to see where I may be going wrong ) .I 'm trying to grab a table i.e . from here : https : //www.oddschecker.com/hor... | url = requests.get ( 'https : //www.oddschecker.com/horse-racing/2020-09-10-haydock/14:00/winner ' ) soup = BeautifulSoup ( url.content , 'lxml ' ) table = soup.find_all ( `` tr '' , class_= '' diff-row evTabRow bc '' ) | Extracting data from list in Python , after BeautifulSoup scrape , and creating Pandas table |
Python | CodeOutputGoalI am intending to split the list , grab the 1st and 2nd words for each section , and put them into a new list.QuestionWhy is my output giving me a weird output ? Where am I going wrong ? Desired OutputMy desired output should look like this : Grabbing the 1st and 2nd words and put them into 1 list . | # Variablesvar1 = [ 'Warehouse Pencil 1.docx ' , 'Production Pen 20.docx ' ] list1 = [ ] for x in var1 : splitted = x.split ( ) a = [ splitted [ 0 ] + ' ' + splitted [ 1 ] ] list1.append ( a ) print ( list1 ) [ [ 'Warehouse Pencil ' ] ] [ [ 'Warehouse Pencil ' ] , [ 'Production Pen ' ] ] [ 'Warehouse Pencil ' , 'Produc... | How to fill a new list while iterating over another list ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.