lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | For example , if our source list is : And I need something like this : I try like this , but this not work correctly : | input = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , ... ] output = { 1 : [ 1 ] , 2 : [ 2,3 ] , 3 : [ 4,5,6 ] , 4 : [ 7,8,9 , ... ] , ... } groups = { } N = 1group = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] for i in range ( 0 , len ( group ) -1 ) : groups.update ( { N : group [ i : i+N ] } ) N+=1 | Slicing a list and group |
Python | I 'm trying to detect contiguous spans in which the relevant variable changes linearly within certain data in a DataFrame . There may be many spans within the data that satisfy this . I started my aproach using ransac based on Robust linear model estimation using RANSAC . However I 'm having issues using the example fo... | import pandas as pdimport matplotlib.pyplot as pltfrom sklearn import linear_model , datasetsimport numpy as np # # 1 . Generate random data for toy sampletimes = pd.date_range ( '2016-08-10 ' , periods=100 , freq='15min ' ) df = pd.DataFrame ( np.random.randint ( 0,100 , size= ( 100 , 1 ) ) , index=times , columns= [ ... | How to detect contiguous spans in which data changes linearly within a DataFrame ? |
Python | During one of the recent code reviews , I 've stumbled upon the problem that was not immediately easy to spot - there was assertTrue ( ) used instead of assertEqual ( ) that basically resulted into a test that was testing nothing . Here is a simplified example : The problem here is that the test would pass ; and techni... | from unittest import TestCaseclass MyTestCase ( TestCase ) : def test_two_things_equal ( self ) : self.assertTrue ( `` a '' , `` b '' ) | Detecting incorrect assertion methods |
Python | When working with built-in types like int and float in Python , it 's common to employ exception handling in cases where input might be unreliable : Are there any prominent edge-cases to be aware of when using str ( ) ? I really do n't like using a broad Exception since there are cases like NameError that signify a pro... | def friendly_int_convert ( val ) : `` Convert value to int or return 37 & print an alert if conversion fails '' try : return int ( val ) except ValueError : print ( 'Sorry , that value doesn\'t work ... I chose 37 for you ! ' ) return 37 def friendly_str_convert ( val ) : `` Convert value to str or return 'yo ! ' & pri... | Potential Exceptions using builtin str ( ) type in Python |
Python | I have a DataFrame that has integers for column names that looks like this : I 'd like to rename the columns . I tried using the followingHowever that does n't change the column names . Do I need to do something else to change column names when they are numbers ? | 1 2 3 4 Red 7 3 2 9 Blue 3 1 6 4 df = df.rename ( columns= { ' 1 ' : 'One ' , ' 2 ' : 'Two ' , ' 3 ' : 'Three ' , ' 4 ' : 'Four ' } ) | Renaming Pandas DataFrame columns that are numbers |
Python | I am trying to do a more elegant version of this code . This just basically appends a string to categorynumber depending on the number . Would appreciate any help . | number = [ 100,150,200,500 ] categoryNumber = [ ] for i in range ( 0 , len ( number ) ) : if ( number [ i ] > =1000 ) : categoryNumber.append ( 'number > 1000 ' ) elif ( number [ i ] > =200 ) : categoryNumber.append ( '200 < number < 300 ' ) elif ( number [ i ] > =100 ) : categoryNumber.append ( '100 < number < 200 ' )... | How to do elif statments more elegantly if appending to array in python |
Python | I am using pythreejs to visualize some 3D models.When visualizing the models on a Jupyter notebook , everything works as expected.But when trying to embed the widget in an HTML document , I am facing two problems : It seems the camera , on load , is looking at ( 0 , 0 , 0 ) , not as expected , and once you interact wit... | from ipywidgets import embedfrom pythreejs import *from IPython.display import displaybase = Mesh ( BoxBufferGeometry ( 20 , 0.1 , 20 ) , MeshLambertMaterial ( color='green ' , opacity=0.5 , transparent=True ) , position= ( 0 , 0 , 0 ) , ) cube = Mesh ( BoxBufferGeometry ( 10 , 10 , 10 ) , MeshLambertMaterial ( color='... | Embed widgets with pythreejs : wrong perspective and camera look-at |
Python | Let 's say I have the following two models : Now I want to calculate the sum of ( field_a * field_b * factor ) of all objects in the Child model . I can calculate the sum of ( field_a * field_b ) with aggregate ( value=Sum ( F ( 'field_a ' ) *F ( 'field_b ' ) , output_field=DecimalField ( ) ) ) . My question is how I c... | class Parent ( models.Model ) : factor = models.DecimalField ( ... ) ... other fieldsclass Child ( models.Model ) : field_a = models.DecimalField ( ... ) field_b = models.DecimalField ( ... ) parent = models.ForeignKey ( Parent ) ... other fields | Django : How do I use a foreign key field in aggregation ? |
Python | I 'm learning python and came across this example of a simulation of a model I 've seen before . One of the functions looked unnecessarily long , so I thought it would be good practice to try to make it more efficient . My attempt , while requiring less code , is about 1/60th as fast . Yes , I made it 60 times worse . ... | def is_unhappy ( self , x , y ) : race = self.agents [ ( x , y ) ] count_similar = 0 count_different = 0 if x > 0 and y > 0 and ( x-1 , y-1 ) not in self.empty_houses : if self.agents [ ( x-1 , y-1 ) ] == race : count_similar += 1 else : count_different += 1 if y > 0 and ( x , y-1 ) not in self.empty_houses : if self.a... | Why is my ( newbie ) code so slow ? |
Python | When working with Python 3 dictionaries , I keep having to do something like this : I seem to remember there being a native way to do this , but was looking through the documentation and could n't find it . Do you know what this is ? | d=dict ( ) if ' k ' in d : d [ ' k ' ] +=1else : d [ ' k ' ] =0 | How to natively increment a dictionary element 's value ? |
Python | I would like to generate a list of all possible 4-tuple pairs given an array of size n. n is at least 8 , so it is always possible to find at least 1 pair . As an example that helps to understand the problem I use a smaller version of the problem , 2-tuple pairs given an arrayy of size 5 . The expected result for 2-tup... | arr = list ( range ( 30 ) ) # example list comb = list ( itertools.combinations ( range ( 0 , len ( arr ) ) , 4 ) ) for c1 in comb : for c2 in comb : # go through all possible pairs if len ( [ val for val in c1 if val in c2 ] ) == 0 : # intersection of both sets results in 0 , so they do n't share an element ... # do s... | Generate all 4-tuple pairs from n elements |
Python | I have these files in my project : main is the main file that will be directly execute in console.module1 will be imported into main and throws Module1Exception.module2 will be imported into module1 , throws Module2Exception and uses lib that throws NormalException and CriticalException exceptions.On all exceptions app... | - main.py- module1.py- module2.py | Python - good practice to catch errors |
Python | I have no idea if this question make much sense or not but i am so confused about it . I have a post list view and it is rendering some of the post here.My question is how can I split the sections of the page.something like this.what should be the approach of making this kind of view.this is my posts view.py posts/view... | class PostListView ( ListView ) : model = Post template_name = 'posts/home.html ' context_object_name = 'posts ' ordering = [ '-date_posted ' ] def get_queryset ( self ) : if not self.request.user.is_authenticated : return Post.objects.all ( ) [ :10 ] else : return super ( ) .get_queryset ( ) from django.db import mode... | how to split post view on the same page in django |
Python | I have a pandas dataframe as such : This represents a tree that looks like thisI want to produce something that looks like this : or What is the fastest way to do so without looping . I have a really large dataframe . | parent child parent_level child_levelA B 0 1B C 1 2B D 1 2X Y 0 2X D 0 2 Y Z 2 3 A X / / \ B / \ /\ / \ C D Y | Z root childrenA [ B , C , D ] X [ D , Y , Z ] root childA BA CA DX DX YX Z | Identifying root parents and all their children in trees |
Python | I 'm trying to figure out how decorator works in python.But , there are two things that I ca n't make clear , so I appreciate it if anyone helps me understand how decorator works in python ! This is the sample code I 've just written to see how it works.OUTPUT 1The first thing I do n't understand is why it outputs `` s... | In [ 22 ] : def deco ( f ) : ... . : def wrapper ( ) : ... . : print ( `` start '' ) ... . : f ( ) ... . : print ( `` end '' ) ... . : return wrapperIn [ 23 ] : @ deco ... . : def test ( ) : ... . : print ( `` hello world '' ) ... . : In [ 24 ] : test ( ) starthello worldend In [ 28 ] : i = deco ( test ) In [ 29 ] : iO... | How decorator works ? |
Python | This is a follow-up and complication to this question : Extracting contents of a string within parentheses.In that question I had the following string -- And I wanted to get a list of tuples in the form of ( actor , character ) -- To generalize matters , I have a slightly more complicated string , and I need to extract... | `` Will Farrell ( Nick Hasley ) , Rebecca Hall ( Samantha ) '' [ ( 'Will Farrell ' , 'Nick Hasley ' ) , ( 'Rebecca Hall ' , 'Samantha ' ) ] `` Will Ferrell ( Nick Halsey ) , Rebecca Hall ( Samantha ) , Glenn Howerton ( Gary ) , with Stephen Root and Laura Dern ( Delilah ) '' [ ( 'Will Farrell ' , 'Nick Hasley ' ) , ( '... | Using regex to extract information from a string |
Python | I have a pandas DataFrame with about 200 columns . Roughly , I want to do thisI 'm not sure what are the best practices when it comes to handling pandas DataFrames , how should I handle this ? Will my pseudocode work , or is it not recommended to modify a pandas dataframe in a for loop ? | for col in df.columns : if col begins with a number : df.drop ( col ) | Delete pandas column if column name begins with a number |
Python | Lets say I have A ( KxMxN ) and B ( KxLxN ) matrices , where L , M , N are small and K is a large number . I would like to calculate the outer product of using the last 2 dimensions along the 1st dimension to get matrix C ( KxMxL ) . I can do this by running a for loop for each index k in `` K '' and use numpy 's matmu... | out = [ np.matmul ( x , y.T ) for x , y in zip ( A , B ) ] out=np.asarray ( out ) | How to efficiently calculate the outer product of two series of matrices in numpy ? |
Python | I 'm a bit baffled why 2to3 is bothering embracing my print arguments that are already in functional style to be wrapped in an extra set of parenthesis . For examplebecomesAre these essentially conservative false positives ? I 'm thinking maybe the trailing ) in the format function is throwing its logic . | print ( `` \t [ Warn ] Can not connect { } '' .format ( ssid ) ) print ( ( `` \t [ Warn ] Can not connect { } '' .format ( ssid ) ) ) | Python 2to3 adding extra parenthesis around functional argument |
Python | I am writing a function that takes in a file object , e.g.The first thing I want to do in the function is ensure that the passed-in file object was opened with newline= '' . How do I do this ? Thanks.PS . I believe this question is only applicable to Python 3 because newline= '' only exists in Python 3 ( note it 's dif... | def my_fn ( file_obj ) : assert < what expression here ? > , `` file_obj must be opened with newline= '' . '' ... | In Python , how to assert passed-in file object was opened with newline= '' ? |
Python | I converted one sample dataframe to .arrow file using pyarrowThis creates a file test.arrowThen in NodeJS I load the file with arrowJS.https : //arrow.apache.org/docs/js/This prints likeI was expecting this table will have a length 3 and table.get ( 0 ) gives the first row instead of null.This is the table scehem looks... | import numpy as npimport pandas as pdimport pyarrow as padf = pd.DataFrame ( { `` a '' : [ 10 , 2 , 3 ] } ) df [ ' a ' ] = pd.to_numeric ( df [ ' a ' ] , errors='coerce ' ) table = pa.Table.from_pandas ( df ) writer = pa.RecordBatchFileWriter ( 'test.arrow ' , table.schema ) writer.write_table ( table ) writer.close ( ... | Converted apache arrow file from data frame gives null while reading with arrow.js |
Python | This question is for fun ; I do n't expect the answer to be useful.When I see people doing things with reduce ( ) in Python , they often take advantage of a builtin function in Python , often from the operator module.This works : But usually you would see this : What 's strange to me is that the operator module does n'... | result = reduce ( lambda a , b : a + b , range ( 5 ) ) from operator import addresult = reduce ( add , range ( 5 ) ) result = reduce ( lambda a , b : a and b , range ( 1 , 6 ) ) from operator import and_result = reduce ( and_ , map ( bool , range ( 1 , 6 ) ) ) result = reduce ( bool.__and__ , map ( bool , range ( 1 , 6... | Is there a builtin function version of ` and ` and/or ` or ` in Python ? |
Python | I 've been trying to learn Python and have come across this issue . I ca n't figure out how the current output came about.I expected the output to be : | d= { 'k1':1 , 'k2':2 , 'k3':3 } for key , value in d.keys ( ) : print ( key ) Output : kkk k1k2k3 | Why isnt the output showing k1 , k2 , k3 ? |
Python | I 'm working on a web server running Python3.6 , Django 2.0 and Channels 2.0.2 . I 'd like to build some tests to make sure my websocket consumers are behaving themselves , unfortunately , whenever I run the tests they are all ignored completely.I 've been following the official Channels documentation on testing , and ... | Creating test database for alias 'default ' ... System check identified no issues ( 0 silenced ) . -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Ran 0 tests in 0.000sOKDestroying test database for alias 'default ' ... | Django Ignoring Asynch Tests Completely ( Django Channels ) |
Python | I 've got the following code which produces the following figureI graphed the data using hexbins , as noted belowI 'd like to change the size of the hexagons based on the density of the points plotted in the area that a hexagon covers . For example , the hexagons in the bottom left ( where the points are compact ) will... | import numpy as npnp.random.seed ( 3 ) import pandas as pdimport matplotlib.pyplot as pltdf = pd.DataFrame ( ) df [ ' X ' ] = list ( np.random.randint ( 100 , size=100 ) ) + list ( np.random.randint ( 30 , size=100 ) ) df [ ' Y ' ] = list ( np.random.randint ( 100 , size=100 ) ) + list ( np.random.randint ( 30 , size=1... | Hex size in matplotlib hexbins based on density of nearby points |
Python | I am starting out with python and trying to construct an XML request for an ebay web service : Now , my question is : Say , this is my function : Where , keyword is the only required field . So , how should I construct the method ? The ways can be : Create an object , pass it to the func ( object ) : The java way Pass ... | def findBestMatchItemDetailsAcrossStores ( ) : request = `` '' '' < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < findBestMatchItemDetailsAcrossStoresRequest xmlns= '' http : //www.ebay.com/marketplace/search/v1/services '' > < siteResultsPerPage > 50 < /siteResultsPerPage > < entriesPerPage > 50 < /entriesPerPa... | **kwargs vs 10 arguments in a python function ? |
Python | I 'm trying to get make an API for the first time and I 've made my app but it says I have to do a local authentication with instructions here : Link to TDAmeritrade authenticationBut it says I have to go on https : //auth.tdameritrade.com/auth ? response_type=code & redirect_uri= { URLENCODED REDIRECT URI } & client_i... | import requestsfrom config import consumer_key # daily prices generatorendpoint = `` https : //api.tdameritrade.com/v1/marketdata/ { } /pricehistory '' .format ( `` AAPL '' ) # parametersimport timetimeStamp=time.time ( ) timeStamp=int ( timeStamp ) parameters = { 'api_key ' : consumer_key , 'periodType ' : 'day ' , 'f... | Authentication for API & Python |
Python | Python 3.8 introduces new shared memory features . We are trying to use the SharedMemoryManager and a NameError is thrown.I thought that we might do something wrong in our complex scenario , so I broke it down using python documentation snippets.This is pretty much taken from the multiprocessing docs ( except for the f... | try : # python > = 3.8 from multiprocessing.managers import SharedMemoryManager as Managerexcept : # python < 3.8 from multiprocessing.managers import BaseManager as Managerclass MathsClass : def add ( self , x , y ) : return x + y def mul ( self , x , y ) : return x * yclass MyManager ( Manager ) : passMyManager.regis... | Why do we get a NameError when trying to use the SharedMemoryManager ( python 3.8 ) as a replacement for the BaseManager ? |
Python | I have a nested list which contains different objects , they 're duplicate pairs of objects in the nested list and i 'm trying to remove them but i keep getting a TypeError : unorderable types : practice ( ) < practice ( ) I know this error is caused by me trying to work with objects rather than integers but i do n't k... | class practice : id = None def __init__ ( self , id ) : self.id = ida = practice ( ' a ' ) b = practice ( ' b ' ) c = practice ( ' c ' ) d = practice ( 'd ' ) e = practice ( ' e ' ) f = practice ( ' f ' ) x = [ [ a , b ] , [ c , d ] , [ a , b ] , [ e , f ] , [ a , b ] ] unique_list = list ( ) for item in x : if sorted ... | How to Sort Python Objects |
Python | With PEP 563 , from __future__ import annotations changes type annotations so that they are evaluated lazily , which provides a bunch of benefits like forward references.However , this seems to play badly with other features , like dataclasses . For example , I have some code that inspects the type parameters of a clas... | from dataclasses import dataclassfrom typing import get_type_hintsclass Foo : pass @ dataclassclass Bar : foo : Fooprint ( get_type_hints ( Bar.__init__ ) ) NameError : name 'Foo ' is not defined | New annotations break inspection of dataclasses |
Python | I have two files - one contains the addresses ( line numbers ) and the other one data , like this : address file : data fileI want to randomize the data file based on the numbers of address filesso I get : I want to do it either in python or in bash , but did n't yet find any solution . | 2467135 1.0004514512.0005892143.1178922784.4795119945.4845148746.7844998747.021239396 2.0005892144.4795119946.7844998747.0212393961.0004514513.1178922785.484514874 | Pick up lines from a file based on line numbers in another file |
Python | Say I have two celery tasks : So when you go to run run_flakey_things it 'll fall over straight away because the first item in the sequence raises an exception . What I would like is to run the task for all items in the sequence in order as map does , but continue to run on exception , raising a new exception once all ... | @ celery.taskdef run_flakey_things ( *args , **kwargs ) : return run_flakey_and_synchronous_thing.map ( xrange ( 10 ) ) .apply_async ( ) @ celery.taskdef run_flakey_and_synchronous_thing ( a ) : if a % 5 : return a raise RuntimeError ( a ) | How to handle errors in celery 's Task.map |
Python | All topics in twitter can be found in this linkI would like to scrape all of them with each of the subcategory inside.BeautifulSoup does n't seem to be useful here . I tried using selenium , but I do n't know how to match the Xpaths that come after clicking the main category.I know I can click the main category using m... | from selenium import webdriverfrom selenium.common import exceptionsurl = 'https : //twitter.com/i/flow/topics_selector'driver = webdriver.Chrome ( 'absolute path to chromedriver ' ) driver.get ( url ) driver.maximize_window ( ) main_topics = driver.find_elements_by_xpath ( '/html/body/div [ 1 ] /div/div/div [ 1 ] /div... | How to scrape all topics from twitter |
Python | I was recently reading some code online , and saw this block : What is happening here ? Why would True ever not be in globals ? I 've never come across anything like this during my ~10 years as a professional python programmer ! | if 'True ' not in globals ( ) : globals ( ) [ 'True ' ] = not None globals ( ) [ 'False ' ] = not True | Why are True and False being set in globals by this code ? |
Python | I 'm trying to implement the fold_by_level SublimeText3 feature on a QScintilla component but I do n't know very well how to do it , so far I 've come up with this code : The docs I 've followed are https : //www.scintilla.org/ScintillaDoc.html # Folding and http : //pyqt.sourceforge.net/Docs/QScintilla2/classQsciScint... | import sysimport reimport mathfrom PyQt5.Qt import * # noqafrom PyQt5.Qsci import QsciScintillafrom PyQt5 import Qscifrom PyQt5.Qsci import QsciLexerCPPclass Foo ( QsciScintilla ) : def __init__ ( self , parent=None ) : super ( ) .__init__ ( parent ) # http : //www.scintilla.org/ScintillaDoc.html # Folding self.setFold... | How to implement SublimeText fold-by-level feature in QScintilla |
Python | I have 110 PDFs that I 'm trying to extract images from . Once the images are extracted , I 'd like to remove any duplicates and delete images that are less than 4KB . My code to do that looks like this : This process can take a while , so I 've started to dabble in multithreading . Feel free to interpret that as me sa... | def extract_images_from_file ( pdf_file ) : file_name = os.path.splitext ( os.path.basename ( pdf_file ) ) [ 0 ] call ( [ `` pdfimages '' , `` -png '' , pdf_file , file_name ] ) os.remove ( pdf_file ) def dedup_images ( ) : os.mkdir ( `` unique_images '' ) md5_library = [ ] images = glob ( `` *.png '' ) print `` Deleti... | How to properly utilize the multiprocessing module in Python ? |
Python | Is there any reason x == x is not evaluated quickly ? I was hoping __eq__ would check if its two arguments are identical , and if so return True instantly . But it does n't do it : For built-ins , x == x always returns True I think ? For user-defined classes , I guess someone could define __eq__ that does n't satisfy t... | s = set ( range ( 100000000 ) ) s == s # this does n't short-circuit , so takes ~1 sec from functools import lru_cache @ lru_cache ( ) def f ( s ) : return sum ( s ) large_obj = frozenset ( range ( 50000000 ) ) f ( large_obj ) # this takes > 1 sec every time def __eq__ ( self , other ) : if self is other : return True ... | Slow equality evaluation for identical objects ( x == x ) |
Python | When in a Python interactive session : On the other hand , when running the following program : The output is : Why a is b has different outcome in the above two cases ? I am aware of this answer ( and of course the difference between the == and is operators ! that is the point of the question ! ) but are n't a and b t... | In [ 1 ] : a = `` my string '' In [ 2 ] : b = `` my string '' In [ 3 ] : a == bOut [ 3 ] : TrueIn [ 4 ] : a is bOut [ 4 ] : FalseIn [ 5 ] : import sysIn [ 6 ] : print ( sys.version ) 3.5.2 ( default , Nov 17 2016 , 17:05:23 ) [ GCC 5.4.0 20160609 ] # ! /usr/bin/env pythonimport sysdef test ( ) : a = `` my string '' b =... | Python not interning strings when in interactive mode ? |
Python | I have an array which looks like this for example : I have another two arrays which are like : and What I want is to pick value 2891 from the 2nd array to the first array in the corresponding position and also 643 from the third array to the first array in the corresponding position so that the final array should look ... | array ( [ [ 1 , 1 , 2 , 0 , 4 ] , [ 5 , 6 , 7 , 8 , 9 ] , [ 10 , 0 , 0 , 13 , 14 ] , [ 15 , 16 , 17 , 18 , 19 ] , [ 20 , 21 , 22 , 0 , 24 ] , [ 25 , 26 , 27 , 28 , 29 ] , [ 30 , 31 , 32 , 33 , 34 ] , [ 35 , 36 , 37 , 38 , 39 ] , [ 40 , 41 , 42 , 43 , 44 ] , [ 45 , 46 , 47 , 48 , 49 ] ] ) array ( [ [ 0 , 0 , 0 , 0 ] , [... | Python numpy array replacing |
Python | I am working on a script that uses itertools to generate desired combinations of given parameters . I am having trouble generating the appropriate 'sets ' however when some variables are linked , i.e . excluding certain combinations . Consider the following : If I want to generate all possible combinations of these ele... | import itertoolsA = [ 'a1 ' , 'a2 ' , 'a3 ' ] B = [ 'b1 ' , 'b2 ' , 'b3 ' ] C = [ 'c1 ' , 'c2 ' ] all_combinations = list ( itertools.product ( A , B , C ) ) [ ( 'a1 ' , 'b1 ' , 'c1 ' ) , ( 'a1 ' , 'b1 ' , 'c2 ' ) , ( 'a1 ' , 'b2 ' , 'c1 ' ) , ... ( 'a3 ' , 'b2 ' , 'c2 ' ) , ( 'a3 ' , 'b3 ' , 'c1 ' ) , ( 'a3 ' , 'b3 ' ... | Python itertools - Create only a subset of all possible products |
Python | The code runs successfully offline , however , when uploaded to a code challenge site it gives me a RuntimeError . I am unsure why it is doing this.My code : Note : `` masing-masing '' in English means `` each '' . `` bersisa '' in English means `` remainder '' .Inputting some test input 15 and 3 gives the expected res... | inputinteger = int ( input ( `` '' ) ) N = inputintegerinputinteger2 = int ( input ( `` '' ) ) M = inputinteger2A = int ( N / M ) if ( N % M == 0 ) : B = 0 print ( `` masing-masing `` + str ( A ) ) print ( `` bersisa `` + str ( B ) ) else : B = int ( N % M ) ; print ( `` masing-masing `` + str ( A ) ) print ( `` bersis... | Runtime error with python code online , works offline |
Python | I have been using PIL ImageI am trying to draw text on an image . I want this text to have a black outline like most memes . I 've attempted to do this by drawing a shadow letter of a bigger font behind the letter in front . I 've adjusted the x and y postions of the shadow accordingly . The shadow is slightly off thou... | from PIL import Image , ImageDraw , ImageFont caption = `` Why is the text slightly off ? '' img = Image.open ( './example-img.jpg ' ) d = ImageDraw.Draw ( img ) x , y = 10 , 400 font = ImageFont.truetype ( font='./impact.ttf ' , size=50 ) shadowFont = ImageFont.truetype ( font='./impact.ttf ' , size=60 ) for idx in ra... | Outline text on image in Python |
Python | I read a post recently where someone mentioned that there is no need for using enums in python . I 'm interested in whether this is true or not.For example , I use an enum to represent modem control signals : Is n't it better that I use if signal == Signals.CTS : than if signal == `` CTS '' : , or am I missing somethin... | class Signals : CTS = `` CTS '' DSR = `` DSR '' ... | No need for enums |
Python | I am writing code to combine functions from the python rawdog RSS reader library and the BeautifulSoup webscraping library . There is a conflict somewhere in the innards that I am trying to overcome . I can replicate the problem with this simplified code : It does not matter what order or where I do the imports , the i... | import sys , gzip def scrape ( filename ) : contents = gzip.open ( filename , 'rb ' ) .read ( ) contents = contents.decode ( 'utf-8 ' , 'replace ' ) import BeautifulSoup as BS print 'before rawdog : ' , len ( BS.BeautifulSoup ( contents ) ) # prints 4 , correct answer from rawdoglib import rawdog as rd print 'after raw... | python conflicts in two external packages |
Python | Where is the difference when I write something on one line , seperated by a , and on two lines . Apparently I do not understand the difference , because I though the two functions below should return the same.But | def fibi ( n ) : a , b = 0 , 1 for i in range ( n ) : a , b = b , a + b return aprint ( fibi ( 6 ) ) > 8 # expected result ( Fibonacci ) def fibi ( n ) : a , b = 0 , 1 for i in range ( n ) : a = b b = a + b return aprint ( fibi ( 6 ) ) > 32 | Difference between writing something on one line and on several lines |
Python | Given a python list of bytes values : How can the list be broken into chunks where each chunk has the maximum memory size below a certain ceiling ? For example : if the ceiling were 7 bytes , then the original list would be broken up into a list of listsAnd each sublist would be at most 7 bytes , based on accumulated l... | # actual str values un-important [ b'foo ' , b'bar ' , b'baz ' , ... ] [ [ b'foo ' , b'bar ' ] , # sublist 0 [ b'baz ' ] , # sublist 1 ... ] | Split a Python List into Chunks with Maximum Memory Size |
Python | Is there any alternative to prevent typing repeated long paths while importing modules in python.Current code : I tried following code : But unfortunately it did not work . I can not do from a.b.c.d.e.f.g import * since there might be too many modules within the ref_path.If I am able to do this , I could easily maintai... | from a.b.c.d.e.f.g import g1from a.b.c.d.e.f.g import g2from a.b.c.d.e.f.g.h import h1from a.b.c.d.e.f.g.i import i1 ref_path = a.b.c.d.e.f.gfrom ref_path import g1from ref_path import g2from ref_path.h import h1from ref_path.i import i1 | Repeated import path patterns in python |
Python | I am learning TensorFlow and was implementing a simple neural network as explained in MNIST for Beginners in TensorFlow docs . Here is the link . The accuracy was about 80-90 % , as expected.Then following the same article was MNIST for Experts using ConvNet . Instead of implementing that I decided to improve the begin... | import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets ( 'MNIST_data ' , one_hot=True ) x = tf.placeholder ( tf.float32 , [ None , 784 ] , 'images ' ) y = tf.placeholder ( tf.float32 , [ None , 10 ] , 'labels ' ) # We are going to make 2 hidden layer neurons w... | Why does this neural network learn nothing ? |
Python | I 'm doing some matrix operations , sometimes involving matrices whose entries have constant values . But for some reason , I can not get the matrix operation to combine the results into a single polynomial , even when the result is simple . for example , consider the following : The problem with this , is that when I ... | from sympy.matrices import *import sympyx= sympy.symbol.symbols ( ' x ' ) Poly_matrix = sympy.Matrix ( [ [ sympy.Poly ( x , x ) ] , [ sympy.Poly ( x , x ) ] ] ) constant_matrix = sympy.Matrix ( [ [ 0,1 ] ] ) constant_matrix_poly = constant_matrix.applyfunc ( lambda val : sympy.Poly ( val , x ) ) # this does n't combine... | How to combine polynomials in matrix operations in Sympy ? |
Python | I 'm trying to sum +1 to some specific cells of a numpy array but I ca n't find any way without slow loops : Resulting in : X [ coords [ : ,0 ] , coords [ : ,1 ] += 1 returnsAny help ? | coords = np.array ( [ [ 1,2 ] , [ 1,2 ] , [ 1,2 ] , [ 0,0 ] ] ) X = np.zeros ( ( 3,3 ) ) for i , j in coords : X [ i , j ] +=1 X = [ [ 1 . 0 . 0 . ] [ 0 . 0 . 3 . ] [ 0 . 0 . 0 . ] ] X = [ [ 1 . 0 . 0 . ] [ 0 . 0 . 1 . ] [ 0 . 0 . 0 . ] ] | Accumulate constant value in Numpy Array |
Python | I have met a snippet of Python 3 code : After I run it , I thought at first that the output should be : But actually the result is : How can this happen ? What happened under the hood ? If I run for i in gen ( ) : print ( i ) , there will be an infinite loop which is what I expected . What is the difference between for... | def gen ( ) : try : while True : yield 1 finally : print ( `` stop '' ) print ( next ( gen ( ) ) ) 1 stop1 | try-finally in Python 3 generator |
Python | I am new to Python and trying to build a practice project that reads some XML . For some reason this if statement is triggered even for blank whitespace lines : Any ideas why ? | if ' < ' and ' > ' in line : | Legit python if statement ? |
Python | I have a script that finds test names and is widely used in our company . It operates on the command line like so : Inside the script is the equivalent of : ( Not sure what all these arguments do , I personally only use the first two ) . These lines are then proceeded by the code that uses these arguments.I want to ref... | find_test.py -- type < type > -- name < testname > import argparseparser = argparse.ArgumentParser ( description='Get Test Path ' ) parser.add_argument ( ' -- type ' , dest='TYPE ' , type=str , default=None , help= '' TYPE [ REQUIRED ] '' ) parser.add_argument ( ' -- name ' , dest='test_name ' , type=str , default=None... | How do I refactor a script that uses argparse to be callable inside another Python script ? |
Python | My structure is thus : companynamespace/__init__.py is emptyprojectpackage/__init__.py has this line : When I open up a python console and type import companynamespace.projectpackage ( PYTHONPATH is set correctly for this ) , I get AttributeError : 'module ' object has no attribute 'projectpackage ' on the import compa... | companynamespace/ __init__.py projectpackage/ __init__.py somemodule.py import companynamespace.projectpackage.somemodule as module_shortname | Package Import woes in Python |
Python | I have found myself many times , with things that I need to be all or at least one equal to something , and I would write something like that : orIf the number of things is small its ok , but it is still not elegant.So , is there a better way for a significant number of things , to do the above ? Thanks . | if a==1 and b==1 : do something if a==1 or b==1 : do something | How do you use OR , AND in conditionals ? |
Python | I 've implemented a python class to generate data as follows : It runs as expected and I get following However , I want to do the same thing for dictionary . Why am I not able to iterate over dictionary like this ? I expect following outputBut when I run above code , I get following error : We can iterate over normal d... | class Array : def __init__ ( self ) : self.arr = [ 1,2,3,4,5,6,7,8 ] def __getitem__ ( self , key ) : return self.arr [ key ] a = Array ( ) for i in a : print ( i , end = `` `` ) 1 2 3 4 5 6 7 8 class Dictionary : def __init__ ( self ) : self.dictionary = { ' a ' : 1 , ' b ' : 2 , ' c ' : 3 } def __getitem__ ( self , k... | Iterating over dictionary using __getitem__ in python |
Python | I have an array of integers of length 150 and the integers range from 1 to 3 . For example , I would like to convert/map/transform Is there an efficient way to do that ? So the outputs is like | array ( [ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 ... | Converting an array of integers to a `` vector '' |
Python | I am trying to wrap an existing C library using cython . The library uses callbacks which I would like to redirect to execute python code.Lets say that the corresponding line in the header is the following : where the return code is used to signal an error . The API tocreate a corresponding C struct is as follows : I a... | typedef RETCODE ( *FUNC_EVAL ) ( int a , int b , void* func_data ) ; RETCODE func_create ( Func** fstar , FUNC_EVAL func_eval , void* func_data ) ; ctypedef RETCODE ( *FUNC_EVAL ) ( int a , int b , void* func_data ) cdef RETCODE func_eval ( int a , int b , void* func_data ) : ( < object > func_data ) .func_eval ( a , b... | Cython function pointers and exceptions |
Python | I have been happily using R for doing data analysis . By data analysis I mean : given a relatively small table ( < 1 mio rows , < 100 columns ) , answer 'complicated ' questions about the data like 'for each instance , what was the last event that happened before a specific point in time varying with the instance ' and... | PROC_ID | SORT_NR A | 1 A | 2 A | 3 A | 4 A | 5 B | 1 B | 2 PROC_ID | SORT_NR A | 1 A | 2 A | 5 < < < 2 was added A | 6 < < < 2 was added A | 7 < < < 2 was added B | 1 B | 2 'EXPERIMENT_NUMBER ' in process_events.columnsOut [ 10 ] : True'EXPERIMENT_ID ' in process_events.columnsOut [ 11 ] : Trueprocess_events.drop ( [ ... | Simple data operations : R vs python |
Python | Let Os be a partially ordered set , and given any two objects O1 and O2 in Os , F ( O1 , O2 ) will return 1 if O1 is bigger than O2 , -1 if O1 is smaller than O2 , 2 if they are incomparable , and 0 if O1 is equal to O2.I need to find the subset Mn of elements is Os that are the minimum . That is for each A in Mn , and... | def GetMinOs ( Os ) : Mn=set ( [ ] ) NotMn=set ( [ ] ) for O1 in Os : for O2 in Os : rel=f ( O1 , O2 ) if rel==1 : NotMn|=set ( [ O1 ] ) elif rel==-1 : NotMn|=set ( [ O2 ] ) Mn=Os-NotMn return Mn | Find in a dynamic pythonic way the minimum elements in a partially ordered set |
Python | Given an object that can be a nested structure of dict-like or array-like objects . What is the pythonic way to set a value on that object given a dotted path as a string ? Example : The above call/assignment should replace the 3 in the example with a 5.Note : The path can contain list indices as well as keys . Every l... | obj = [ { ' a ' : [ 1 , 2 ] } , { ' b ' : { ' c ' : [ 3 , 4 ] , } } , ] path = ' 1.b.c.0 ' # operation that sets a value at the given path , e.g.obj [ path ] = 5 # orset_value ( obj , path , 5 ) | How to set attribute on an object given a dotted path ? |
Python | I have the following function : I 'm running mypy , and it 's telling me that NotImplemented is of type `` Any '' , which it obviously does n't like.Is there any better type I can use to remove this error ? Or should I just put a type : ignore in and move on ? ( In addition , is my use of NotImplemented in the return t... | def __eq__ ( self , other : object ) - > Union [ bool , NotImplemented ] : try : for attr in [ `` name '' , `` variable_type '' ] : if getattr ( self , attr ) ! = getattr ( other , attr ) : return False return True except AttributeError : return NotImplemented # Expression has type `` Any '' | What is the type of NotImplemented ? |
Python | Found this puzzle inside an image . According to my thinking the total number of ways should be2*comb ( 7 , i ) for i < - 1 to 7 where comb is defined as follows . Is my approach correct ? I am concerned with the result that I get and not the function written below.Do n't mind me asking too many questions in a short ti... | def comb ( N , k ) : if ( k > N ) or ( N < 0 ) or ( k < 0 ) : return 0L N , k = map ( long , ( N , k ) ) top = N val = 1L while ( top > ( N-k ) ) : val *= top top -= 1 n = 1L while ( n < k+1L ) : val /= n n += 1 return val | combinatorics implementation and puzzle |
Python | The following python code uses PyOpenCL to fill the array a_plus_b with the sum of the elements in array b ( this is n't my actual objective , but it 's the simplest code I can find that still shows the problem ) .Gives the output : However , if I change width from 32 to 33 , the array is no longer the same element ove... | import pyopencl as climport numpy as npimport numpy.linalg as laheight = 50width = 32b = np.arange ( width , dtype=np.int32 ) ctx = cl.create_some_context ( ) queue = cl.CommandQueue ( ctx ) mf = cl.mem_flagsb_buf = cl.Buffer ( ctx , mf.READ_ONLY | mf.COPY_HOST_PTR , hostbuf=b ) dest_buf = cl.Buffer ( ctx , mf.WRITE_ON... | Why is this opencl code non-deterministic ? |
Python | In java , I use the function all the time . Is there an equivalent function in python ? | variable = something == 1 ? 1 : 0 | Equivalent for ? in Java for Python ? |
Python | I have found a similar question here , but the answer does not seem to work for me.I use Flask User ( which extends Flask Login , I believe ) and for the most part it works very well . I have built my own completely fresh templates for sign in and registration , rather than using their provided ones . Following the doc... | app = Flask ( __name__ ) @ app.context_processordef inject_production_status ( ) : return dict ( production=True ) # Initialise flask_loginlogin = LoginManager ( app ) login.login_view = 'login'login.refresh_view = `` login '' login.needs_refresh_message = `` Please sign in again to access this page '' user_manager = U... | Overriding Flask-User/Flask-Login 's default templates |
Python | I have 2-time series data frames . Both contain values [ 0,1 ] only . The first one is called init_signal and the second is called end_signal . The idea is to create a new data frame when init_signal has a 1 , it will find the NEXT 1 in end_signal.The example below merges both the init_signal and end_signal as one data... | 2016-06-13 1 02016-06-14 0 02016-06-15 0 12016-06-16 0 0 2016-06-13 1 2016-06-14 1 2016-06-15 1 2016-06-16 0 2016-06-13 1 12016-06-14 0 02016-06-15 0 12016-06-16 0 0 2016-06-13 1 2016-06-14 1 2016-06-15 1 2016-06-16 0 | Setting values given two column |
Python | The Python docs say that the metaclass of a class can be any callable . All the examples I see use a class . Why not use a function ? It 's callable , and fairly simple to define . But it is n't working , and I do n't understand why.Here 's my code : Here 's the output : The metaclass method is defined for both the par... | class Foo ( object ) : def __metaclass__ ( name , base , dict ) : print ( 'inside __metaclass__ ( % r , ... ) ' % name ) return type ( name , base , dict ) print ( Foo.__metaclass__ ) class Bar ( Foo ) : passprint ( Bar.__metaclass__ ) inside __metaclass__ ( 'Foo ' , ... ) < unbound method Foo.__metaclass__ > < unbound... | Why is n't my metaclass function getting invoked for subclasses ? |
Python | I have some data stored in a list that I would like to group based on a value.For example , if my data isand I want to group it by the first value in each tuple to gethow would I go about it ? More generally , what 's the recommended way to group data in python ? Is there a recipe that can help me ? | data = [ ( 1 , ' a ' ) , ( 2 , ' x ' ) , ( 1 , ' b ' ) ] result = [ ( 1 , 'ab ' ) , ( 2 , ' x ' ) ] | A recipe to group/aggregate data ? |
Python | I 'm using argparse to manage command line options , and I want manage two options , -- check and -- nocheck.I 'm actually doing something like this in mybadscript.py : The problem is that if launch the script this way : python mybadscript.py -- nocheck -- checkcheck will be set to False . This is incorrect , since the... | [ ... ] args = parser.parse_args ( ) if args.check : check = Trueif args.nocheck : check = False [ ... ] | How to manage precedence in argparse ? |
Python | I want to split a string like : intoWhat 's an elegant way to do this in Python ? If it makes it easier , it can be assumed that the string will only contain a 's , b 's and c 's . | 'aaabbccccabbb ' [ 'aaa ' , 'bb ' , 'cccc ' , ' a ' , 'bbb ' ] | Split string into strings of repeating elements |
Python | I am trying to generate a 2D vector from a 1D vector where the element is shifted along the row by an increment each row . i would like my input to look like this : im unaware of a way to do this without using a for loop , and computational efficieny is important for the task im using this for . Is there a way to do th... | input : t = [ t1 , t2 , t3 , t4 , t5 ] out = [ t5 , 0 , 0 , 0 , 0 ] [ t4 , t5 , 0 , 0 , 0 ] [ t3 , t4 , t5 , 0 , 0 ] [ t2 , t3 , t4 , t5 , 0 ] [ t1 , t2 , t3 , t4 , t5 ] [ 0 , t1 , t2 , t3 , t4 ] [ 0 , 0 , t1 , t2 , t3 ] [ 0 , 0 , 0 , t1 , t2 ] [ 0 , 0 , 0 , 0 , t1 ] import numpy as npt = np.linspace ( -3 , 3 , 7 ) z =... | mapping a 2d delay vector from a 1d vector in numpy |
Python | What I 'm trying to do is recursively process a list . I 'm new to python so when all the code was written and sent to be executed I faced a strange problem : the list returns changed after calling the recursive function . To test this I wrote that : And called the function : Here was the result : What I expected to se... | def recur ( n ) : n.append ( len ( n ) ) print ' > ' , n if n [ -1 ] < 5 : recur ( n ) print ' < ' , n recur ( [ ] ) > [ 0 ] > [ 0 , 1 ] > [ 0 , 1 , 2 ] > [ 0 , 1 , 2 , 3 ] > [ 0 , 1 , 2 , 3 , 4 ] > [ 0 , 1 , 2 , 3 , 4 , 5 ] < [ 0 , 1 , 2 , 3 , 4 , 5 ] < [ 0 , 1 , 2 , 3 , 4 , 5 ] < [ 0 , 1 , 2 , 3 , 4 , 5 ] < [ 0 , 1 ,... | python : recurcive list processing changes original list |
Python | The following code models a system that can sample 3 different states at any time , and the constant transition probability between those states is given by the matrix prob_nor . Threrefore , each point in trace depends on the previous state.The loop in the above code makes it run pretty slow , specially when I have to... | n_states , n_frames = 3 , 1000state_val = np.linspace ( 0 , 1 , n_states ) prob = np.random.randint ( 1 , 10 , size= ( n_states , ) *2 ) prob [ np.diag_indices ( n_states ) ] += 50prob_nor = prob/prob.sum ( 1 ) [ : ,None ] # transition probability matrix , # row sum normalized to 1.0state_idx = range ( n_states ) # sta... | Vectorize numpy code with operation depending on previous value |
Python | I 'm looking for a clean way to do this in Python : Let 's say I have two iterators `` iter1 '' and `` iter2 '' : perhaps a prime number generator , and itertools.count ( ) . I know a priori that both are are infinite and monotonically increasing . Now I want to take some simple operation of two args `` op '' ( perhaps... | import operatordef powers_of_ten ( ) : n = 0 while True : yield 10**n n += 1def series_of_nines ( ) : yield 1 n = 1 while True : yield int ( `` 9 '' *n ) n += 1op = operator.muliter1 = powers_of_ten ( ) iter2 = series_of_nines ( ) # given ( iter1 , iter2 , op ) , create an iterator that yields : # [ 1 , 9 , 10 , 90 , 9... | `` sorted 1-d iterator '' based on `` 2-d iterator '' ( Cartesian product of iterators ) |
Python | this was in a recent test of mine and i just ca n't get list comprehension down . So basically this function was supposed to return the length of the largest list ( which is what i 'm assuming based on the correct answers ) I would have understood that if it were n't for this part of the function : when i see that part... | def a ( n ) : return max ( [ len ( n ) ] + [ a ( i ) for i in n ] ) if isinstance ( n , list ) else 0 + [ a ( i ) for i in n ] ) | Can you explain the following function ? |
Python | I have a dataframe that looks like this : I want to have one bar for old freq and one for new freq . Currently I have graph that looks like this : This is what the code looks like : How do I add another bar ? Explanation about DF : It has frequencies relevant to each hour in a specific date.Edit : One approach could be... | freq_df [ 'date ' ] = pd.to_datetime ( freq_df [ 'date ' ] ) freq_df [ 'hour ' ] = freq_df [ 'hour ' ] .astype ( str ) fig = px.bar ( freq_df , x= '' hour '' , y= '' old freq '' , hover_name = `` date '' , animation_frame= freq_df.date.dt.day ) fig.update_layout ( transition = { 'duration ' : 2000 } ) , date , hour , o... | Plotly : How to animate a bar chart with multiple groups using plotly express ? |
Python | I 'm trying to submit a PR for scikit-image , but I get a Travis-CI error : I suppose that this might be a circular import error , but I do n't quite get how to resolve the issue . I 've already included frangi_filter and hessian_filter into filter 's module __init__.py.I 've also tried relative import , which resulted... | Traceback ( most recent call last ) : File `` doc/examples/edges/plot_canny.py '' , line 22 , in < module > from skimage import feature File `` /home/travis/build/scikit-image/scikit-image/skimage/feature/__init__.py '' , line 9 , in < module > from .peak import peak_local_max File `` /home/travis/build/scikit-image/sc... | Trouble with relative / absolute functions import in scikit-image |
Python | I 'm using Python 's `` re '' module as follows : All I 'm doing is getting the HTML of this site , and looking for this particular snippet of code : However , it continues to print an empty array . Why is this ? Why ca n't re.findall find this snippet ? | request = get ( `` http : //www.allmusic.com/album/warning-mw0000106792 '' ) print re.findall ( ' < hgroup > ( .* ? ) < /hgroup > ' , request ) < hgroup > < h3 class= '' album-artist '' > < a href= '' http : //www.allmusic.com/artist/green-day-mn0000154544 '' > Green Day < /a > < /h3 > < h2 class= '' album-title '' > W... | Python 's `` re '' module not working ? |
Python | I 've been experimenting with Python as a begninner for the past few hours . I wrote a recursive function , that returns recurse ( x ) as x ! in Python and in Java , to compare the two . The two pieces of code are identical , but for some reason , the Python one works , whereas the Java one does not . In Python , I wro... | x = int ( raw_input ( `` Enter : `` ) ) def recurse ( num ) : if num ! = 0 : num = num * recurse ( num-1 ) else : return 1 return num print recurse ( x ) public class Default { static Scanner input = new Scanner ( System.in ) ; public static void main ( String [ ] args ) { System.out.print ( `` Enter : `` ) ; int x = i... | Why do these two similar pieces of code produce different results ? |
Python | Consider two functions of SymPy symbols e and i : This will produceHowever , assume that e and i are both small and we can neglect both terms that are order three or higher . Using Sympy ’ s series tool or simply adding an O-notation Order class can handle this : Looks great . However , I am still left with mixed terms... | from sympy import Symbol , expand , Orderi = Symbol ( ' i ' ) e = Symbol ( ' e ' ) f = ( i**3 + i**2 + i + 1 ) g = ( e**3 + e**2 + e + 1 ) z = expand ( f*g ) z = e**3*i**3 + e**3*i**2 + e**3*i + e**3 + e**2*i**3 + e**2*i**2 + e**2*i + e**2 + e*i**3 + e*i**2 + e*i + e + i**3 + i**2 + i + 1 In : z = expand ( f*g + Order ... | Remove mixed-variable terms in SymPy series expansion |
Python | I have a DataFrame : I want to calculate how many times a transition has occurred . Here in the ID column a- > b is considered as a transition , similarly for b- > d , d- > d , d- > a , b- > c , c- > b , b- > a . I can do this using Counter like : I also need to get min and max of the sec column of those transitions . ... | df = pd.DataFrame ( { 'ID ' : [ ' a ' , ' b ' , 'd ' , 'd ' , ' a ' , ' b ' , ' c ' , ' b ' , 'd ' , ' a ' , ' b ' , ' a ' ] , 'sec ' : [ 3,6,2,0,4,7,10,19,40,3,1,2 ] } ) print ( df ) ID sec0 a 31 b 62 d 23 d 04 a 45 b 76 c 107 b 198 d 409 a 310 b 111 a 2 Counter ( zip ( df [ 'ID ' ] .to_list ( ) , df [ 'ID ' ] .to_lis... | Calculate min and max value of a transition with index of first occurrence in pandas |
Python | I 'm relatively new to Python and would like to know if I 'm reinventing a wheel or do things in a non-pythonic way - read wrong.I 'm rewriting some parser originally written in Lua . There is one function which accepts a field name from imported table and its value , does some actions on value and stores it in target ... | class TransformTable : target_dict = { } ... def mapfield ( self , fieldname , value ) : try : { 'productid ' : self.fn_prodid , 'name ' : self.fn_name , 'description ' : self.fn_desc , ... } [ fieldname ] ( value ) except KeyError : sys.stderr.write ( 'Unknown key ! \n ' ) def fn_name ( val ) : validity_check ( val ) ... | Dictionary based switch-like statement with actions |
Python | I 've just upgraded to Canopy 1.7.1 ; I think this problem stems from the change in IPython version from 2.4.1 to 4.1.2.The issue I have is that calling a DataFrame object in Python seems to use the __print__ method , i.e . there 's no difference between typing print df and df into the interpreter , and unfortunately t... | date flag1 20151102 098663 20151101 1 from IPython.core.display import display , HTMLdisplay ( HTML ( ' < h1 > Hello , world ! < /h1 > ' ) ) < IPython.core.display.HTML object > | HTML not rendering properly with Canopy 1.7.1.3323 / IPython 4.1.2 |
Python | When I have to compare the contents of two array-like objects -- for instance lists , tuples or collection.deques -- without regard for the type of the objects , I useIs there any more idiomatic/faster/better way to achieve this ? | list ( an_arrayish ) == list ( another_arrayish ) | What are the best ways to compare the contents of two list-like objects ? |
Python | How can I create a list from another list using python ? If I have a list : How can I create the list of only those letters that follow slash `` / '' i.e.A code would be very helpful . | input = [ ' a/b ' , ' g ' , ' c/d ' , ' h ' , ' e/f ' ] desired_output = [ ' b ' , 'd ' , ' f ' ] | How to create a list from another list using specific criteria in Python ? |
Python | I am interested in calculating a large NumPy array . I have a large array A which contains a bunch of numbers . I want to calculate the sum of different combinations of these numbers . The structure of the data is as follows : My question is if there is a more elegant and memory efficient way to calculate this ? I find... | A = np.random.uniform ( 0,1 , ( 3743 , 1388 , 3 ) ) Combinations = np.random.randint ( 0,3 , ( 306,3 ) ) Final_Product = np.array ( [ np.sum ( A*cb , axis=2 ) for cb in Combinations ] ) | Vectorize large NumPy multiplication |
Python | I implemented exponentially weighted moving average ( ewma ) in python3 and in Haskell ( compiled ) . It takes about the same time . However when this function is applied twice , haskell version slows down unpredictably ( more than 1000 times , whereas python version is only about 2 times slower ) . Python3 version : H... | import numpy as npdef ewma_f ( y , tau ) : a = 1/tau avg = np.zeros_like ( y ) for i in range ( 1 , len ( y ) ) : avg [ i ] = a*y [ i-1 ] + ( 1-a ) *avg [ i-1 ] return avg ewmaL : : [ Double ] - > Double - > [ Double ] ewmaL ys tau = reverse $ e ( reverse ys ) ( 1.0/tau ) where e [ x ] a = [ a*x ] e ( x : xs ) a = ( a*... | Similar code ( for exponentially weighted deviation ) is slower in Haskell than in Python |
Python | I 'm searching for the best algorithm to resolve this problem : having a list ( or a dict , a set ) of small sentences , find the all occurrences of this sentences in a bigger text . The sentences in the list ( or dict , or set ) are about 600k but formed , on average , by 3 words . The text is , on average , 25 words ... | to_find_sentences = [ 'bla bla ' , 'have a tea ' , 'hy i m luca ' , ' i love android ' , ' i love ios ' , ... .. ] text = ' i love android and i think i will have a tea with john'def find_sentence ( to_find_sentences , text ) : text = text.split ( ) res = [ ] w = len ( text ) for i in range ( w ) : for j in range ( i+1... | Find lots of string in text - Python |
Python | I have a ( large ) integer array likewith few unique entries and I 'd like to convert it into a dictionary of indices , i.e. , What 's the most efficient way of doing so ? ( NumPy welcome . ) | materials = [ 0 , 0 , 47 , 0 , 2 , 2 , 47 ] # ... d = { 0 : [ 0 , 1 , 3 ] , 2 : [ 4 , 5 ] , 47 : [ 2 , 6 ] , } | Convert array of integers into dictionary of indices |
Python | The following reverses a list `` in-place '' and works in Python 2 and 3 : Why/how ? Since reversed gives me an iterator and does n't copy the list beforehand , and since [ : ] = replaces `` in-place '' , I am surprised . And the following , also using reversed , breaks as expected : Why does n't the [ : ] = fail like ... | > > > mylist = [ 1 , 2 , 3 , 4 , 5 ] > > > mylist [ : ] = reversed ( mylist ) > > > mylist [ 5 , 4 , 3 , 2 , 1 ] > > > mylist = [ 1 , 2 , 3 , 4 , 5 ] > > > for i , item in enumerate ( reversed ( mylist ) ) : mylist [ i ] = item > > > mylist [ 5 , 4 , 3 , 4 , 5 ] | Why does ` mylist [ : ] = reversed ( mylist ) ` work ? |
Python | for convenience I want to create subclasses of datetime.timedelta . The idea is to define a class as such : so I can quickly create timedeltas like that : However , the code above produces a timedelta of n days instead of n hours . As an example , look at the following ipython session : I 'm not able to explain this . ... | class Hours ( datetime.timedelta ) : def __init__ ( self , hours ) : super ( Hours , self ) .__init__ ( hours=hours ) x = Hours ( n ) In [ 1 ] : import datetimeIn [ 2 ] : class Hours ( datetime.timedelta ) : ... : def __init__ ( self , hours ) : ... : super ( Hours , self ) .__init__ ( hours=hours ) ... : In [ 3 ] : pr... | Strange behaviour when subclassing datetime.timedelta |
Python | I 'm looking to reverse a set of strings while keeping them in the same positions and also trying not to use slicing or reverse ( ) . So if I had : Using the reverse function , it would return : I made a function that does everything correct except for positioning : which returns ; How can I get this reversed string ba... | string = 'This is the string ' 'sihT si eht gnirts ' def Reverse ( string ) : length = len ( string ) emp = `` '' for i in range ( length-1 , -1 , -1 ) : emp += length [ i ] return emp gnirts a si sihT # correct reverse , wrong positions | Reversing string characters while keeping them in the same position |
Python | I 've tried all the solutions mentioned on the internet so far nothing worked for me.I have a python code , to speed it up , I want that my code runs the heavy calculations in a C function.I already wrote this C function.Then , to share the library , I did this in the terminal : which returns no error . The problem ; c... | gcc -shared -Wl , -install_name , testlib.so -o testlib.so -fPIC myModule.c int multiplier ( int a , int b ) { int lol = 0 ; lol = a*b ; return lol ; } import ctypeszelib = ctypes.CDLL ( `` /Users/longeard/Desktop/Codes/DraII/testlib.so '' , ctypes.RTLD_GLOBAL ) res = zelib.multiplier ( 2,3 ) 6 float multiplier ( float... | Using a C function in Python |
Python | I 'm writing a metaclass , and I want an additional method to be called between __new__ and __init__ . If I were calling the method before __new__ or after __init__ I could write e.g.My temptation is to writeand just reproduce the functionality of type.__call__ myself . But I 'm afraid there might be some subtlety to t... | class Meta ( type ) : def __call__ ( cls ) : ret = type.__call__ ( ) ret.extraMethod ( ) class Meta ( type ) : def __call__ ( cls ) : ret = cls.__new__ ( cls ) ret.extraMethod ( ) ret.__init__ ( ) return ret | Does the default type.__call__ do more than call __new__ and __init__ ? |
Python | Python 's built-in xml.etree package supports parsing XML files with namespaces , but namespace prefixes get expanded to the full URI enclosed in brackets . So in the example file in the official documentation : The actor tag gets expanded to { http : //people.example.com } actor and fictional : character to { http : /... | < actors xmlns : fictional= '' http : //characters.example.com '' xmlns= '' http : //people.example.com '' > < actor > < name > John Cleese < /name > < fictional : character > Lancelot < /fictional : character > < fictional : character > Archie Leach < /fictional : character > < /actor > ... | How can I make my code more readable and DRYer when working with XML namespaces in Python ? |
Python | I would like to write a data converter tool . I need analyze the bitstream in a file to display the 2D cross-sections of a 3D volume.The dataset I am trying to view can be found here : https : //figshare.com/articles/SSOCT_test_dataset_for_OCTproZ/12356705.It 's the file titled : burned_wood_with_tape_1664x512x256_12bi... | import rawpyimport imageiopath = `` Datasets/burned_wood_with_tape_1664x512x256_12bit.raw '' for item in path : item_path = path + item raw = rawpy.imread ( item_path ) rgb = raw.postprocess ( ) rawpy.imshow ( rgb ) | Using a Data Converter to Display 3D Volume as Images |
Python | Suppose i have a project structure like thisI want to check which file uses a class or a function from another file . I have a class called Test in main.pyI used that class in model_a , But in model_b i usedI want to to check which file uses another file , just like tree command , just a folder name is enough so i trie... | src└── app ├── main.py ├── db │ └── database.py ├── models │ ├── model_a.py │ └── model_b.py └── tests ├── test_x.py └── test_y.py class Test : pass from ..main import Test from ..main import Testfrom ..db.database import Data from app.db import databasefrom app.models import model_a , model_bfrom app.tests import test... | How to check does a file imports from another file in Python |
Python | I am trying to send 100 requests at a time to a server http : //httpbin.org/uuid using the following code snippet I am using FastAPI with Asyncio to achieve the lowest time possible around 3 seconds or less but using the above method I am getting an overall time of 66 seconds that is more than a minute . I also want to... | from fastapi import FastAPIfrom time import sleepfrom time import timeimport requestsimport asyncioapp = FastAPI ( ) URL= `` http : //httpbin.org/uuid '' # @ app.get ( `` / '' ) async def main ( ) : r = requests.get ( URL ) # print ( r.text ) return r.textasync def task ( ) : tasks = [ main ( ) , main ( ) , main ( ) , ... | How can I send an HTTP request from my FastAPI app to another site ? |
Python | Why on Earth does n't the interpreter raise SyntaxError everytime I do this : I just wanted to add ' c ' to the list of strings , and forgot to append the comma . I would expect this to cause some kind of error , as it 's cleary incorrect . Instead , what I got : And this is never what I want . Why is it automatically ... | my_abc = [ ' a ' , ' b ' , ' c ' 'd ' , ] > > > my_abc [ ' a ' , ' b ' , 'cd ' ] | Problem with list of strings in python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.