id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
12,100 | holding stock can be more complicated the adjusted close values used here have been adjusted for splits and dividendshowever in all casesit' quite common to derive return indexwhich is time series indicating the value of unit investment (one dollarsaymany assumptions can underlie the return indexfor examplesome will ch... |
12,101 | - - - - - - freqm - - if you had dividend dates and percentagesincluding them in the total return per day would look likereturns[dividend_dates+dividend_pcts group transforms and analysis in you learned the basics of computing group statistics and applying your own transformations to groups in dataset let' consider col... |
12,102 | financial tech - - in [ ]by_industry describe(out[ ]momentum shortinterest value industry financial count mean - std min - - - - max - tech count mean - std min - - - - max - by defining transformation functionsit' easy to transform these portfolios by industry for examplestandardizing within industry is widely used in... |
12,103 | you could do this by chaining together rank and zscore like soindustry rank and standardize in [ ]by_industry apply(lambda xzscore( rank())out[ ]index entriesvtkgn to ptdqe data columnsmomentum non-null values shortinterest non-null values value non-null values dtypesfloat ( group factor exposures factor analysis is te... |
12,104 | too much additional random noise added to the portfolio using groupby you can compute exposures industry by industry to do sowrite function like sodef beta_exposure(chunkfactors=none)return pd ols( =chunkx=factorsbeta thengroup by industries and apply that functionpassing the dataframe of factor loadingsin [ ]by_ind po... |
12,105 | index ( retscumprod(first_loc max(index notnull(argmax( index values[first_loc return index def trend_signal(retslookbacklag)signal pd rolling_sum(retslookbackmin_periods=lookback return signal shift(lagusing this functionwe can (naivelycreate and test trading strategy that trades this momentum signal every fridayin [ ... |
12,106 | return rets mean(rets std(np sqrt(annnowdividing vol into quartiles with qcut and aggregating with sharpe we obtainin [ ]trade_rets groupby(pd qcut(vol )agg(sharpeout[ ][ ( ( - ( these results show that the strategy performed the best during the period when the volatility was the highest more example applications here ... |
12,107 | compute portfolio weights freq '%dbhold port calc_mom(priceslblag= daily_rets prices pct_change(compute portfolio returns port port shift( resample(freqhow='first'returns daily_rets resample(freqhow=compoundport_rets (port returnssum(axis= return daily_sr(port_retsnp sqrt( holdfigure - cumulative returns for each of th... |
12,108 | ddf index name 'holding periodddf columns name 'lookback periodto visualize the results and get an idea of what' going onhere is function that uses matplotlib to produce heatmap with some adornmentsimport matplotlib pyplot as plt def heatmap(dfcmap=plt cm gray_r)fig plt figure(ax fig add_subplot( axim ax imshow(df valu... |
12,109 | of each contract for exampleat any given time for type of future (say silver or copper futuresmultiple contracts with different expiration dates may be traded in many casesthe future contract expiring next (the near contractwill be the most liquid (highest volume and lowest bid-ask spreadfor the purposes of modeling an... |
12,110 | simulate the two contracts into the futurenp random seed( walk (np random randint( size= perturb (np random randint( size= walk walk cumsum(rng pd date_range(px index[ ]periods=len(pxnfreq=' 'near np concatenate([px valuespx values[- walk]far np concatenate([px valuespx values[- walk perturb]prices dataframe({'esu 'nea... |
12,111 | the weights look like this around the esu expiryin [ ]weights get_roll_weights(''expiryprices columnsin [ ]weights ix['':''out[ ]esu esz finallythe rolled future returns are just weighted sum of the contract returnsin [ ]rolled_returns (prices pct_change(weightssum( rolling correlation and linear regression dynamic mod... |
12,112 | non-null values intercept non-null values dtypesfloat ( in [ ]model beta['msft'plot(figure - one-year correlation of apple with microsoft figure - one-year beta (ols regression coefficientof apple to microsoft pandas' ols function implements static and dynamic (expanding or rolling windowleast squares regressions for m... |
12,113 | |
12,114 | advanced numpy ndarray object internals the numpy ndarray provides means to interpret block of homogeneous data (either contiguous or stridedmore on this lateras multidimensional array object as you've seenthe data typeor dtypedetermines how the data is interpreted as being floating pointintegerbooleanor any of the oth... |
12,115 | figure - the numpy ndarray object numpy dtype hierarchy you may occasionally have code which needs to check whether an array contains integersfloating point numbersstringsor python objects because there are many types of floating point numbers (float through float )checking that the dtype is among list of types would b... |
12,116 | advanced array manipulation there are many ways to work with arrays beyond fancy indexingslicingand boolean subsetting while much of the heavy lifting for data analysis applications is handled by higher level functions in pandasyou may at some point need to write data algorithm that is not found in one of the existing ... |
12,117 | [ ]]one of the passed shape dimensions can be - in which case the value used for that dimension will be inferred from the datain [ ]arr np arange( in [ ]arr reshape(( - )out[ ]array([ ] ] ] ][ ]]since an array' shape attribute is tupleit can be passed to reshapetooin [ ]other_arr np ones(( )in [ ]other_arr shape out[ ]... |
12,118 | that if you have two-dimensional array of datathe items in each row of the array are stored in adjacent memory locations the alternative to row major ordering is column major orderwhich means that (you guessed itvalues within each column of data are stored in adjacent memory locations for historical reasonsrow and colu... |
12,119 | [ ]]in [ ]np concatenate([arr arr ]axis= out[ ]array([ ] ]]figure - reshaping in (row majoror fortran (column majororder there are some convenience functionslike vstack and hstackfor common kinds of concatenation the above operations could have been expressed asin [ ]np vstack((arr arr )out[ ]array([ ] ] ][ ]]in [ ]np ... |
12,120 | in [ ]second out[ ]array([ ]]in [ ]third out[ ]array([[- ] ]] ] ]]see table - for list of all relevant concatenation and splitting functionssome of which are provided only as convenience of the very general purpose concatenate table - array concatenation functions function description concatenate most general functionc... |
12,121 | the need to replicate or repeat arrays is less common with numpy than it is with other popular array programming languages like matlab the main reason for this is that broadcasting fulfills this need betterwhich is the subject of the next section the two main tools for repeating or replicating arrays to produce larger ... |
12,122 | can visually think about it as like "laying down tiles"in [ ]arr out[ ]array([ - ] ]]in [ ]np tile(arr out[ ]array([ - - ] ]]the second argument is the number of tileswith scalarthe tiling is made row-byrowrather than column by columnthe second argument to tile can be tuple indicating the layout of the "tiling"in [ ]ar... |
12,123 | out[ ]array( ]to use take along other axesyou can pass the axis keywordin [ ]inds [ in [ ]arr randn( in [ ]arr out[ ]array([[- - - ] - ]]in [ ]arr take(indsaxis= out[ ]array([[- - - ] - ]]put does not accept an axis argument but rather indexes into the flattened (one-dimensionalc orderversion of the array (this could b... |
12,124 | the multiplication operation for examplewe can demean each column of an array by subtracting the column means in this caseit is very simplein [ ]arr randn( in [ ]arr mean( out[ ]array( ]in [ ]demeaned arr arr mean( in [ ]demeaned out[ ]array([ - - ][- - ][- - ] - ]]in [ ]demeaned mean( out[ ]array( - - ]see figure - fo... |
12,125 | matches according to the rulesto subtract over axis (that issubtract the row mean from each row)the smaller array must have shape ( )in [ ]arr out[ ]array([ - ] ][- ] - ]]in [ ]row_means arr mean( in [ ]row_means reshape(( )out[ ]array([ ] ] ] ]]in [ ]demeaned arr row_means reshape(( )in [ ]demeaned mean( out[ ]array( ... |
12,126 | valueerroroperands could not be broadcast together with shapes ( , ( figure - broadcasting over axis of array it' quite common to want to perform an arithmetic operation with lower dimensional array across axes other than axis according to the broadcasting rulethe "broadcast dimensionsmust be in the smaller array in th... |
12,127 | ][- ]]figure - compatible array shapes for broadcasting over array thusif we had three-dimensional array and wanted to demean axis saywe would only need to writein [ ]arr randn( in [ ]depth_means arr mean( in [ ]depth_means out[ ]array([ - ] - ] - ]]in [ ]demeaned arr depth_means[::np newaxisin [ ]demeaned mean( out[ ]... |
12,128 | without sacrificing performance there isin factbut it requires some indexing gymnasticsdef demean_axis(arraxis= )means arr mean(axisthis generalized things like [::np newaxisto dimensions indexer [slice(none)arr ndim indexer[axisnp newaxis return arr means[indexersetting array values by broadcasting the same broadcasti... |
12,129 | each of numpy' binary ufuncs has special methods for performing certain kinds of special vectorized operations these are summarized in table - but 'll give few concrete examples to illustrate how they work reduce takes single array and aggregates its valuesoptionally along an axisby performing sequence of binary operat... |
12,130 | out[ ]array([ ]in [ ]np multiply outer(arrnp arange( )out[ ]array([[ ][ ][ ][ ][ ]]the output of outer will have dimension that is the sum of the dimensions of the inputsin [ ]result np subtract outer(randn( )randn( )in [ ]result shape out[ ]( the last methodreduceatperforms "local reduce"in essence an array groupby op... |
12,131 | there are couple facilities for creating your own functions with ufunc-like semantics numpy frompyfunc accepts python function along with specification for the number of inputs and outputs for examplea simple function that adds element-wise would be specified asin [ ]def add_elements(xy)return in [ ]add_them np frompyf... |
12,132 | out[ ]array([( )( - )]dtype=[(' ''< ')(' ''< ')]there are several ways to specify structured dtype (see the online numpy documentationone typical way is as list of tuples with (field_namefield_data_typenowthe elements of the array are tuple-like objects whose elements can be accessed like dictionaryin [ ]sarr[ out[ ]( ... |
12,133 | in [ ]data np array([(( ) )(( ) )]dtype=dtypein [ ]data[' 'out[ ]array([( )( )]dtype=[(' ''< ')(' ''< ')]in [ ]data[' 'out[ ]array([ ]dtype=int in [ ]data[' '][' 'out[ ]array( ]as you can seevariable-shape fields and nested records is very rich feature that can be the right tool in certain circumstances dataframe from ... |
12,134 | like python' built-in listthe ndarray sort instance method is an in-place sortmeaning that the array contents are rearranged without producing new arrayin [ ]arr randn( in [ ]arr sort(in [ ]arr out[ ]array([- ]when sorting arrays in-placeremember that if the array is view on different ndarraythe original array will be ... |
12,135 | in [ ]arr out[ ]array([[- - [- - - [- - - ] ] ]]you may notice that none of the sort methods have an option to sort in descending order this is not actually big deal because array slicing produces viewsthus not producing copy or requiring any computational work many python users are familiar with the "trickthat for lis... |
12,136 | out[ ]array([ ][- - - ] - - ]]lexsort is similar to argsortbut it performs an indirect lexicographical sort on multiple key arrays suppose we wanted to sort some data identified by first and last namesin [ ]first_name np array(['bob''jane''steve''bill''barbara']in [ ]last_name np array(['jones''arnold''arnold''jones''w... |
12,137 | performance (and performance guaranteesthis is not something that most users will ever have to think about but useful to know that it' there table - array sorting methods kind speed stable work space worst-case 'quicksort no ( 'mergesort yes / ( log 'heapsort no ( log nat the time of this writingsort algorithms other t... |
12,138 | array( ] to then get labeling of which interval each data point belongs to (where would mean the bucket [ ))we can simply use searchsortedin [ ]labels bins searchsorted(datain [ ]labels out[ ]array([ ]thiscombined with pandas' groupbycan be used to easily bin datain [ ]series(datagroupby(labelsmean(out[ ] note that num... |
12,139 | out[ ]array([ [- - ] ] ] ]]in [ ] out[ ]array([ ] ][- ] ]]in this casethe product yt would be expressed like soin [ ]np dot( tnp dot(xy)out[ ]array([ ]]to aid in writing code with lot of matrix operationsnumpy has matrix class which has modified indexing behavior to make it more matlab-likesingle rows and columns come ... |
12,140 | they are generally more seldom used in individual functions with lots of linear algebrait may be helpful to convert the function argument to matrix typethen cast back to regular arrays with np asarray (which does not copy any databefore returning them advanced array input and output in introduced you to np save and np ... |
12,141 | ]]]]in [ ]del mmap whenever memory map falls out of scope and is garbage-collectedany changes will be flushed to disk also when opening an existing memory mapyou still have to specify the dtype and shape as the file is just block of binary data with no metadata on diskin [ ]mmap np memmap('mymmap'dtype='float 'shape=( ... |
12,142 | by numpy alonewriting code in cfortranor especially cython (see bit more on this belowmay be in order personally use cython (own work as an easy way to get -like performance with minimal development the importance of contiguous memory while the full extent of this topic is bit outside the scope of this bookin some appl... |
12,143 | invest some effort if you have an array that does not have the desired memory orderyou can use copy and pass either 'cor ' 'in [ ]arr_f copy(' 'flags out[ ]c_contiguous true f_contiguous false owndata true writeable true aligned true updateifcopy false when constructing view on an arraykeep in mind that the result is n... |
12,144 | wrapper generator for fortran and codeand writing pure extensions performance tips www it-ebooks info |
12,145 | |
12,146 | python language essentials knowledge is treasurebut practice is the key to it --thomas fuller people often ask me about good resources for learning python for data-centric applications while there are many excellent python language booksi am usually hesitant to recommend some of them as they are intended for general au... |
12,147 | facility with pythonthe languagethe easier it will be for you to prepare new data sets for analysis the python interpreter python is an interpreted language the python interpreter runs program by executing one statement at time the standard interactive python interpreter can be invoked on the command line with the pyth... |
12,148 | standard prompt the basics language semantics the python language design is distinguished by its emphasis on readabilitysimplicityand explicitness some people go so far as to liken it to "executable pseudocodeindentationnot braces python uses whitespace (tabs or spacesto structure code instead of using braces as in man... |
12,149 | love it or hate itsignificant whitespace is fact of life for python programmersand in my experience it helps make python code lot more readable than other languages 've used while it may seem foreign at firsti suspect that it will grow on you after while strongly recommend that you use spaces to as your default indenta... |
12,150 | functions are called using parentheses and passing zero or more argumentsoptionally assigning the returned value to variableresult (xyzg(almost every object in python has attached functionsknown as methodsthat have access to the object' internal contents they can be called using the syntaxobj some_method(xyzfunctions c... |
12,151 | an object variables names that have been assigned may occasionally be referred to as bound variables when you pass objects as arguments to functionyou are only passing referencesno copying occurs thuspython is said to pass by referencewhereas some other languages support both pass by value (creating copiesand pass by r... |
12,152 | in [ ] string formattingto be visited later in [ ]print ' is %sb is % (type( )type( ) is is in [ ] out[ ] knowing the type of an object is importantand it' useful to be able to write functions that can handle many different kinds of input you can check that an object is an instance of particular type using the isinstan... |
12,153 | often you may not care about the type of an object but rather only whether it has certain methods or behavior for exampleyou can verify that an object is iterable if it implemented the iterator protocol for many objectsthis means it has __iter__ "magic method"though an alternative and better way to check is to try usin... |
12,154 | import some_module as sm from some_module import pi as pig as gf sm (pir gf( pibinary operators and comparisons most of the binary math operations and comparisons are as you might expectin [ ] out[ ]- in [ ] out[ ] in [ ] < out[ ]false see table - for all of the available binary operators to check if two references ref... |
12,155 | description * raise to the power true if both and are true for integerstake the bitwise and true if either or is true for integerstake the bitwise or for booleanstrue if or is truebut not both for integerstake the bitwise exclusive-or = true if equals ! true if is not equal to <ba true if is less than (less than or equ... |
12,156 | in [ ]a_tuple ( ( )in [ ]a_tuple[ 'fourtypeerror traceback (most recent call lastin (---- a_tuple[ 'fourtypeerror'tupleobject does not support item assignment remember that just because you can mutate an object does not mean that you always should such actions are known in programming as side effects for examplewhen wr... |
12,157 | each one is double-precision ( bitsvalue they can also be expressed using scientific notationin [ ]fval in [ ]fval - in python integer division not resulting in whole number will always yield floating point numberin [ ] out[ ] in python and below (which some readers will likely be using)you can enable this behavior by ... |
12,158 | in [ ] [ 'ftypeerror traceback (most recent call lastin (---- [ 'ftypeerror'strobject does not support item assignment in [ ] replace('string''longer string'in [ ] out[ ]'this is longer stringmany python objects can be converted to string using the str functionin [ ] in [ ] str(ain [ ] out[ ]' strings are sequence of c... |
12,159 | so has expanded with the advent of python here will briefly describe the mechanics of one of the main interfaces strings with followed by one or more format characters is target for inserting value into that string (this is quite similar to the printf function in cas an exampleconsider this stringin [ ]template ' % are... |
12,160 | out[ ](falsetruein [ ]bool('hello world!')bool(''out[ ](truefalsein [ ]bool( )bool( out[ ](falsetruetype casting the strboolint and float types are also functions which can be used to cast values to those typesin [ ] ' in [ ]fval float(sin [ ]int(fvalout[ ] in [ ]type(fvalout[ ]float in [ ]bool(fvalout[ ]true in [ ]boo... |
12,161 | out[ ] in [ ]dt minute out[ ] given datetime instanceyou can extract the equivalent date and time objects by calling methods on the datetime of the same namein [ ]dt date(out[ ]datetime date( in [ ]dt time(out[ ]datetime time( the strftime method formats datetime as stringin [ ]dt strftime('% /% /% % :% 'out[ ] : strin... |
12,162 | else block if all of the conditions are falseif print 'it' negativeelif = print 'equal to zeroelif print 'positive but smaller than elseprint 'positive and larger than or equal to if any of the conditions is trueno further elif or else blocks will be reached with compound condition using and or orconditions are evaluat... |
12,163 | (tuples or listssay)they can be conveniently unpacked into variables in the for loop statementfor abc in iteratordo something while loops while loop specifies condition and block of code that is to be executed until the condition evaluates to false or the loop is explicitly ended with breakx total while if total break ... |
12,164 | valueerrorcould not convert string to floatsomething suppose we wanted version of float that fails gracefullyreturning the input argument we can do this by writing function that encloses the call to float in tryexcept blockdef attempt_float( )tryreturn float(xexceptreturn the code in the except part of the block will o... |
12,165 | (the parentheses are required)def attempt_float( )tryreturn float(xexcept (typeerrorvalueerror)return in some casesyou may not want to suppress an exceptionbut you want some code to be executed regardless of whether the code in the try block succeeds or not to do thisuse finallyf open(path' 'trywrite_to_file(ffinallyf ... |
12,166 | all numbers from to that are multiples of or sum for in xrange( )is the modulo operator if = or = sum + in python range always returns an iteratorand thus it is not necessary to use the xrange function ternary expressions ternary expression in python allows you combine an if-else block which produces value into single ... |
12,167 | tuple is one-dimensionalfixed-lengthimmutable sequence of python objects the easiest way to create one is with comma-separated sequence of valuesin [ ]tup in [ ]tup out[ ]( when defining tuples in more complicated expressionsit' often necessary to enclose the values in parenthesesas in this example of creating tuple of... |
12,168 | that many copies of the tuple in [ ]('foo''bar' out[ ]('foo''bar''foo''bar''foo''bar''foo''bar'note that the objects themselves are not copiedonly the references to them unpacking tuples if you try to assign to tuple-like expression of variablespython will attempt to unpack the value on the right-hand side of the equal... |
12,169 | out[ ] list in contrast with tupleslists are variable-length and their contents can be modified they can be defined using square brackets [or using the list type functionin [ ]a_list [ nonein [ ]tup ('foo''bar''baz'in [ ]b_list list(tupin [ ]b_list out[ ]['foo''bar''baz'in [ ]b_list[ 'peekabooin [ ]b_list out[ ]['foo''... |
12,170 | in [ ]b_list remove('foo'in [ ]b_list out[ ]['red''baz''dwarf''foo'if performance is not concernby using append and removea python list can be used as perfectly suitable "multi-setdata structure you can check if list contains value using the in keywordin [ ]'dwarfin b_list out[ ]true note that checking whether list con... |
12,171 | in [ ] out[ ][ sort has few options that will occasionally come in handy one is the ability to pass secondary sort keyi function that produces value to use to sort the objects for examplewe could sort collection of strings by their lengthsin [ ] ['saw''small''he''foxes''six'in [ ] sort(key=lenin [ ] out[ ]['he''saw''si... |
12,172 | out[ ][ while element at the start index is includedthe stop index is not includedso that the number of elements in the result is stop start either the start or stop can be omitted in which case they default to the start of the sequence and the end of the sequencerespectivelyin [ ]seq[: out[ ][ in [ ]seq[ :out[ ][ nega... |
12,173 | it' common when iterating over sequence to want to keep track of the index of the current item do-it-yourself approach would look likei for value in collectiondo something with value + since this is so commonpython has built-in function enumerate which returns sequence of (ivaluetuplesfor ivalue in enumerate(collection... |
12,174 | is determined by the shortest sequencein [ ]seq [falsetruein [ ]zip(seq seq seq out[ ][('foo''one'false)('bar''two'true) very common use of zip is for simultaneously iterating over multiple sequencespossibly also combined with enumeratein [ ]for (abin enumerate(zip(seq seq ))print('% % % (iab) fooone bartwo bazthree gi... |
12,175 | out[ ]{' ''some value'' '[ ]elements can be accessed and inserted or set using the same syntax as accessing elements of list or tuplein [ ] [ 'an integerin [ ] out[ ]{ 'an integer'' ''some value'' '[ ]in [ ] [' 'out[ ][ you can check if dict contains key using the same syntax as with checking whether list or tuple cont... |
12,176 | it' common to occasionally end up with two sequences that you want to pair up element-wise in dict as first cutyou might write code like thismapping {for keyvalue in zip(key_listvalue_list)mapping[keyvalue since dict is essentially collection of -tuplesit should be no shock that the dict type function accepts list of -... |
12,177 | the built-in collections module has useful classdefaultdictwhich makes this even easier one is created by passing type or function for generating the default value for each slot in the dictfrom collections import defaultdict by_letter defaultdict(listfor word in wordsby_letter[word[ ]append(wordthe initializer to defau... |
12,178 | out[ ]set([ ]sets support mathematical set operations like unionintersectiondifferenceand symmetric difference see table - for list of commonly used set methods in [ ] { in [ ] { in [ ] union (orout[ ]set([ ]in [ ] intersection (andout[ ]set([ ]in [ ] difference out[ ]set([ ]in [ ] symmetric difference (xorout[ ]set([ ... |
12,179 | list comprehensions are one of the most-loved python language features they allow you to concisely form new list by filtering the elements of collection and transforming the elements passing the filter in one conscise expression they take the basic form[expr for val in collection if conditionthis is equivalent to the f... |
12,180 | dict and set comprehensions were added to python fairly recently in python and python nested list comprehensions suppose we have list of lists containing some boy and girl namesin [ ]all_data [['tom''billy''jefferson''andrew''wesley''steven''joe']['susie''casey''jill''ana''eva''jennifer''stephanie']you might have gotte... |
12,181 | three levels of nesting you should probably start to question your data structure design it' important to distinguish the above syntax from list comprehension inside list comprehensionwhich is also perfectly validin [ ][[ for in tupfor tup in some_tuplesfunctions functions are the primary and most important method of c... |
12,182 | [for in range( ) append(iupon calling func()the empty list is created elements are appendedthen is destroyed when the function exits suppose instead we had declared [def func()for in range( ) append(iassigning global variables within function is possiblebut those variables must be declared as global using the global ke... |
12,183 | when first programmed in python after having programmed in java and ++one of my favorite features was the ability to return multiple values from function here' simple exampledef () return abc abc (in data analysis and other scientific applicationsyou will likely find yourself doing this very often as many functions may... |
12,184 | value value strip(value re sub('[!#?]'''valueremove punctuation value value title(result append(valuereturn result the result looks like thisin [ ]clean_strings(statesout[ ]['alabama''georgia''georgia''georgia''florida''south carolina''west virginia'an alternate approach that you may find useful is to make list of the ... |
12,185 | 'georgia''florida''south carolina''west virginia'anonymous (lambdafunctions python has support for so-called anonymous or lambda functionswhich are really just simple functions consisting of single statementthe result of which is the return value they are defined using the lambda keywordwhich has no meaning other than ... |
12,186 | closures are nothing to fear they can actually be very useful and powerful tool in the right circumstancein nutshella closure is any dynamically-generated function returned by another function the key property is that the returned function has access to the variables in the local namespace where it was created here is ... |
12,187 | count[ + return count[ return counter counter make_counter(you might be wondering why this is useful in practiceyou can write very general functions with lots of optionsthen fabricate simplermore specialized functions here' an example of creating string formatting functiondef format_and_pad(templatespace)def formatter(... |
12,188 | args is ( kwargs is {' ' hellonow ' going to call out[ ] curryingpartial argument application currying is fun computer science term which means deriving new functions from existing ones by partial argument application for examplesuppose we had trivial function that adds two numbers togetherdef add_numbers(xy)return usi... |
12,189 | out[ ]any iterator is any object that will yield objects to the python interpreter when used in context like for loop most methods expecting list or list-like object will also accept any iterable object this includes built-in methods such as minmaxand sumand type constructors like list and tuplein [ ]list(dict_iterator... |
12,190 | print way [ [ [ [ [ [ in [ ]len(list(make_change( ))out[ ] generator expresssions simple way to make generator is by using generator expression this is generator analogue to listdict and set comprehensionsto create oneenclose what would otherwise be list comprehension with parenthesis instead of bracketsin [ ]gen ( * f... |
12,191 | ['albert' ['steven'see table - for list of few other itertools functions 've frequently found useful table - some useful itertools functions function description imap(func*iterablesgenerator version of the built-in mapapplies func to each zipped tuple of the passed sequences generator version of the built-in filteryiel... |
12,192 | ['sue\xc \xb el rico en su riqueza,''que \xc \xa cuidados le ofrece;''''sue\xc \xb el pobre que padece''su miseria su pobreza;''''sue\xc \xb el que medrar empieza,''sue\xc \xb el que afana pretende,''sue\xc \xb el que agravia ofende,'''' en el mundoen conclusi\xc \xb ,''todos sue\xc \xb an lo que son,''aunque ninguno l... |
12,193 | method description read([size]return data from file as stringwith optional size argument indicating the number of bytes to read readlines([size]return list of lines in the filewith optional size argument readlines([size]return list of lines (as stringsin the file write(strwrite passed string to file writelines(stringsw... |
12,194 | symbols character !operator !cmd command "two-languageproblem - (hash mark) $path variable character % datetime format % datetime format %alias magic function %automagic magic function % datetime format % datetime format %bookmark magic function % datetime format %cd magic function %cpaste magic function - % datetime f... |
12,195 | donation statistics by occupation and employer - donation statistics by state - =operator prompt (question mark) [(brackets) (backslash) (underscore) __ (two underscores) {(braces) operator file mode abs function accumulate method add method add_patch method add_subplot method aggfunc option aggregate method aggregatio... |
12,196 | concatenating along - labels for - renaming indexes for - swapping in arrays - axessubplot object axis argument axis method broadcasting - defined over other axes - setting array values by bucketing - file mode backslash (\) bar plots - basemap object bashrc file bash_profile file bbox_inches option benefits of python ... |
12,197 | along axis - arrays - conditional logic as array operation - conferences configuring matplotlib - conforming contains method contiguous memory - continue keyword continuous return convention argument converting between string and datetime - timestamps to periods coordinated universal time (utc) copy argument copy metho... |
12,198 | concatenating along axis - dataframe merges - on index - pivoting - reshaping - transforming data - discretization - dummy variables - filtering outliers - mapping - permutation removing duplicates - renaming axis indexes - replacing values - usda food database example - databases reading and writing to - dataframe dat... |
12,199 | edgecolo option edit-compile-run workflow eig function elif blocks (see if statementselse block (see if statementsempty function empty namespace encoding argument endswith method enumerate function environment variables epd (enthought python distribution) - equal function escapechar option ewma function ewmcorr functio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.