id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
11,800 | in [ ]df boys[boys year = in [ ]in df sort_index(by='prop'ascending=falseprop cumsum(in [ ]in searchsorted( out[ ] it should now be fairly straightforward to apply this operation to each year/sex combinationgroupby those fields and apply function returning the count for each groupdef get_quantile_count(groupq= )group g... |
11,801 | have only become more so over time further analysis of what exactly is driving the diversitylike the increase of alternate spellingsis left to the reader the "last letterrevolution in baby name researcher laura wattenberg pointed out on her website (http//www babynamewizard comthat the distribution of boy names by fina... |
11,802 | letter_prop[' 'plot(kind='bar'rot= ax=axes[ ]title='male'letter_prop[' 'plot(kind='bar'rot= ax=axes[ ]title='female'legend=falsefigure - proportion of boy and girl names ending in each letter as you can seeboy names ending in "nhave experienced significant growth since the going back to the full table created abovei ag... |
11,803 | boy names that became girl names (and vice versaanother fun trend is looking at boy names that were more popular with one sex earlier in the sample but have "changed sexesin the present one example is the name lesley or leslie going back to the top dataseti compute list of names occurring in the dataset starting with '... |
11,804 | cols='sex'aggfunc='sum'in [ ]table table div(table sum( )axis= in [ ]table tail(out[ ]sex year nan nan nan nan nan lastlyit' now easy to make plot of the breakdown by sex over time (figure - )in [ ]table plot(style={' '' -'' '' --'}figure - proportion of male/female lesley-like names over time conclusions and the path ... |
11,805 | |
11,806 | ipythonan interactive computing and development environment act without doingwork without effort think of the small as large and the few as many confront the difficult while it is still easyaccomplish the great task by series of small acts --laozi people often ask me"what is your python development environment?my answe... |
11,807 | ipythoni recommend that you follow along with the examples to get feel for how things work as with any keyboard-driven console-like environmentdeveloping muscle-memory for the common commands is part of the learning curve many parts of this (for exampleprofiling and debuggingcan be safely omitted on first reading as th... |
11,808 | which is distinct from normal printing with print if you printed dict like the above in the standard python interpreterit would be much less readablefrom numpy random import randn data { randn(for in range( )print data { - - - ipython also provides facilities to make it easy to execute arbitrary blocks of code (via som... |
11,809 | underscoressuch as magic methods and internal "privatemethods and attributesin order to avoid cluttering the display (and confusing new python users!thesetoocan be tab-completed but you must first type an underscore to see them if you prefer to always see such methods in tab completionyou can change this setting in the... |
11,810 | return then using shows us the docstringin [ ]add_numberstypefunction string formfilebook_scriptsdefinitionadd_numbers(abdocstringadd two numbers together returns the_sum type of arguments using ?will also show the function' source code if possiblein [ ]add_numbers?typefunction string formfilebook_scriptsdefinitionadd_... |
11,811 | result (abcthis can be executed by passing the file name to %runin [ ]%run ipython_script_test py the script is run in an empty namespace (with no imports or other variables definedso that the behavior should be identical to running the program on the command line using python script py all of the variables (importsfun... |
11,812 | line into ipythonand line breaks are treated as this means that if you paste code with an indented block and there is blank lineipython will think that the indented block is over once the next line in the block is executedan indentationer ror will be raised for example the following codex if + will not work if simply p... |
11,813 | + :-with the %cpaste blockyou have the freedom to paste as much code as you like before executing it you might decide to use %cpaste in order to look at the pasted code before executing it if you accidentally paste the wrong codeyou can break out of the %cpaste prompt by pressing lateri'll introduce the ipython html no... |
11,814 | command description ctrl- or up-arrow search backward in command history for commands starting with currently-entered text ctrl- or down-arrow search forward in command history for commands starting with currently-entered text ctrl- readline-style reverse history search (partial matchingctrl-shift- paste text from clip... |
11,815 | can be controlled using the %xmode magic commandfrom minimal (same as the standard python interpreterto verbose (which inlines function argument values and moreas you will see later in the you can step into the stack (using the %debug or %pdb magicsafter an error has occurred for interactive post-mortem debugging magic... |
11,816 | is defined with the same name as the magic function in question this feature is called automagic and can be enabled or disabled using %automagic since ipython' documentation is easily accessible from within the systemi encourage you to explore all of the special commands available by typing %quickref or %magic will hig... |
11,817 | matplotlib integration and pylab mode part of why ipython is so widely used in scientific computing is that it is designed as companion to libraries like matplotlib and other gui toolkits don' worry if you have never used matplotlib beforeit will be discussed in much more detail later in this book if you create matplot... |
11,818 | with the shell the typical way to launch ipython with matplotlib integration is by adding the -pylab flag (two dashesipython --pylab this will cause several things to happen first ipython will launch with the default gui backend integration enabled so that matplotlib plot windows can be created with no issues secondlym... |
11,819 | ipython maintains small on-disk database containing the text of each command that you execute this serves various purposessearchingcompletingand executing previously-executed commands with minimal typing persisting the command history between sessions logging the input/output history to file searching and reusing the c... |
11,820 | out[ ] in [ ] out[ ] input variables are stored in variables named like _ixwhere is the input line number for each such input variables there is corresponding output variable _x so after input line saythere will be two new variables (for the outputand _i for the input in [ ]foo 'barin [ ]foo out[ ]'barin [ ]_i out[ ] '... |
11,821 | state false active ipython logging can be enabled at any time and it will record your entire session (including previous commandsthusif you are working on something and you decide you want to save everything you didyou can simply enable logging see the docstring of %logstart for more options (including changing the out... |
11,822 | python |epd ( -bit)(defaultjul : : [gcc (red hat - )on linux type "packages""demoor "enthoughtfor more information the console output of shell command can be stored in variable by assigning the !escaped expression to variable for exampleon my linux-based machine connected to the internet via etherneti can get my ip add... |
11,823 | ipython has simple directory bookmarking system to enable you to save aliases for common directories so that you can jump around very easily for examplei' an avid user of dropboxso can define bookmark to make it easy to change directories to my dropboxin [ ]%bookmark db /home/wesm/dropboxonce 've done thiswhen use the ... |
11,824 | works_fine(--- throws_an_exception( calling_things(/home/wesm/book_scripts/ch /ipython_bug py in throws_an_exception( ---- assert( = def calling_things()assertionerrorin [ ]%debug /home/wesm/book_scripts/ch /ipython_bug py( )throws_an_exception( ---- assert( = ipdbonce inside the debuggeryou can execute arbitrary pytho... |
11,825 | examplein the above exceptionwe could set breakpoint right before calling the works_fine method and run the script until we reach the breakpoint by pressing (continue)ipdbb ipdbc /home/wesm/book_scripts/ch /ipython_bug py( )calling_things( def calling_things() -- works_fine( throws_an_exception(at this pointyou can ste... |
11,826 | to an ideyou might find the terminal-driven debugger to be bit bewildering at firstbut that will improve in time most of the python ides have excellent gui debuggersbut it is usually significant productivity gain to remain in ipython for your debugging table - ( )python debugger commands command action (elpdisplay comm... |
11,827 | throws_an_exception(pressing (continuewill cause the code to resume normally with no harm done the debug function above enables you to invoke the interactive debugger easily on an arbitrary function call suppose we had written function like def (xyz= )tmp return tmp and we wished to step through its logic ordinarily us... |
11,828 | for larger-scale or longer-running data analysis applicationsyou may wish to measure the execution time of various components or of individual statements or function calls you may want report of which functions are taking up the most time in complex process fortunatelyipython enables you to get this information very ea... |
11,829 | loopsbest of ms per loop this seemingly innocuous example illustrates that it is worth understanding the performance characteristics of the python standard librarynumpypandasand other libraries used in this book in larger-scale data analysis applicationsthose milliseconds will start to add up%timeit is especially usefu... |
11,830 | cprofile by running the following in the command linepython - cprofile cprof_example py if you try thatyou'll find that the results are outputted sorted by function name this makes it bit hard to get an idea of where the most time is spentso it' very common to specify sort order using the - flagpython - cprofile - cumu... |
11,831 | {numpy linalg lapack_lite dgeev {method 'randn' linalg py: (_assertfinite {method 'allof 'numpy ndarrayobjectssimilarlycalling %run - - cumulative cprof_example py has the same effect as the command-line approach aboveexcept you never have to leave ipython profiling function line-by-line in some cases the information y... |
11,832 | {method 'sumof 'numpy ndarrayobjects : ( {method 'disableof '_lsprof profilerobjectsthis is not especially enlightening with the line_profiler ipython extension activateda new command %lprun is available the only difference in usage is that we must instruct %lprun which function or functions we wish to profile the gene... |
11,833 | you want to profile with %lprun is that the overhead of "tracingthe execution time of each line is significant tracing functions that are not of interest would potentially significantly alter the profile results ipython html notebook starting in the ipython teamled by brian grangerbuilt web technology-based interactive... |
11,834 | ipython in mind to be easier to work with than code intended only to be run as as standalone command-line application this becomes especially important when something goes wrong and you have to diagnose an error in code that you or someone else might have written months or years beforehand tips for productive code deve... |
11,835 | in pythonwhen you type import some_libthe code in some_lib is executed and all the variablesfunctionsand imports defined within are stored in the newly created some_lib module namespace the next time you type import some_libyou will get reference to the existing module namespace the potential difficulty in interactive ... |
11,836 | it' not unusual to see program written for the command line with structure somewhat like the following trivial examplefrom my_functions import def (xy)return ( ydef main() result if __name__ ='__main__'main(do you see what might be wrong with this program if we were to run it in ipythonafter it' donenone of the results... |
11,837 | put all of your code in single monstrous file finding sensible and intuitive module and package structure for large codebase often takes bit of workbut it is especially important to get right in teams each module should be internally cohesiveand it should be as obvious as possible where to find functions and classes re... |
11,838 | most aspects of the appearance (colorspromptspacing between linesetc and behavior of the ipython shell are configurable through an extensive configuration system here are some of the things you can do via configurationchange the color scheme change how the input and output prompts lookor remove the blank line after out... |
11,839 | as alwaysthe online ipython documentation is an excellent resource for more on profiles and configuration credits parts of this were derived from the wonderful documentation put together by the ipython development team can' thank them enough for all of their work building this amazing set of tools ipythonan interactive... |
11,840 | numpy basicsarrays and vectorized computation numpyshort for numerical pythonis the fundamental package required for high performance scientific computing and data analysis it is the foundation on which nearly all of the higher-level tools in this book are built here are some of the things it providesndarraya fast and ... |
11,841 | fast vectorized array operations for data munging and cleaningsubsetting and filteringtransformationand any other kinds of computations common array algorithms like sortinguniqueand set operations efficient descriptive statistics and aggregating/summarizing data data alignment and relational data manipulations for merg... |
11,842 | out[ ]dtype('float 'this will introduce you to the basics of using numpy arraysand should be sufficient for following along with the rest of the book while it' not necessary to have deep understanding of numpy for many data analytical applicationsbecoming proficient in array-oriented programming and thinking is key ste... |
11,843 | out[ ]dtype('int 'in addition to np arraythere are number of other functions for creating new arrays as exampleszeros and ones create arrays of ' or 'srespectivelywith given length or shape empty creates an array without initializing its values to any particular value to create higher dimensional array with these metho... |
11,844 | description emptyempty_like create new arrays by allocating new memorybut do not populate with any values like ones and zeros eyeidentity create square identity matrix ( ' on the diagonal and ' elsewheredata types for ndarrays the data type or dtype is special object containing the information the ndarray needs to inte... |
11,845 | type code description float or extended-precision floating point complex complex complex complex numbers represented by two or floatsrespectively bool boolean type storing true and false values object python object type string_ fixed-length string type ( byte per characterfor exampleto create string dtype with length u... |
11,846 | in [ ]int_array astype(calibers dtypeout[ ]array( ]there are shorthand type code strings you can also use to refer to dtypein [ ]empty_uint np empty( dtype=' 'in [ ]empty_uint out[ ]array( ]dtype=uint calling astype always creates new array ( copy of the data)even if the new dtype is the same as the old dtype it' worth... |
11,847 | in more detail in having deep understanding of broadcasting is not necessary for most of this book basic indexing and slicing numpy array indexing is rich topicas there are many ways you may want to select subset of your data or individual elements one-dimensional arrays are simpleon the surface they act similarly to p... |
11,848 | need to explicitly copy the arrayfor example arr[ : copy(with higher dimensional arraysyou have many more options in two-dimensional arraythe elements at each index are no longer scalars but rather one-dimensional arraysin [ ]arr np array([[ ][ ][ ]]in [ ]arr [ out[ ]array([ ]thusindividual elements can be accessed rec... |
11,849 | [ ][ ]]]arr [ is arrayin [ ]arr [ out[ ]array([[ ][ ]]both scalar values and arrays can be assigned to arr [ ]in [ ]old_values arr [ copy(in [ ]arr [ in [ ]arr out[ ]array([[[ ][ ]][ ][ ]]]in [ ]arr [ old_values in [ ]arr out[ ]array([[ ] ]][ ][ ]]]similarlyarr [ gives you all of the values whose indices start with ( )... |
11,850 | [ ][ ]]array([[ ][ ]]as you can seeit has sliced along axis the first axis slicethereforeselects range of elements along an axis you can pass multiple slices just like you can pass multiple indexesin [ ]arr [: :out[ ]array([[ ][ ]]when slicing like thisyou always obtain array views of the same number of dimensions by m... |
11,851 | ] - - ]]figure - two-dimensional array slicing suppose each name corresponds to row in the data array if we wanted to select all the rows with corresponding name 'boblike arithmetic operationscomparisons (such as ==with arrays are also vectorized thuscomparing names with the string 'bobyields boolean arrayin [ ]names =... |
11,852 | ]]in [ ]data[names ='bob' out[ ]array( ]to select everything but 'bob'you can either use !or negate the condition using -in [ ]names !'bobout[ ]array([falsetruetruefalsetruetruetrue]dtype=boolin [ ]data[-(names ='bob')out[ ]array([[- - ][- - ][- - ] ] - - ]]selecting two of the three names to combine multiple boolean c... |
11,853 | in [ ]data[names !'joe' in [ ]data out[ ]array([ ] ] ] ] ] ] ]]fancy indexing fancy indexing is term adopted by numpy to describe indexing using integer arrays suppose we had arrayin [ ]arr np empty(( )in [ ]for in range( )arr[ii in [ ]arr out[ ]array([ ] ] ] ] ] ] ] ]]to select out subset of the rows in particular ord... |
11,854 | elements corresponding to each tuple of indicesmore on reshape in in [ ]arr np arange( reshape(( )in [ ]arr out[ ]array([ ] ] ][ ][ ][ ][ ][ ]]in [ ]arr[[ ][ ]out[ ]array( ]take moment to understand what just happenedthe elements ( )( )( )and ( were selected the behavior of fancy indexing in this case is bit different ... |
11,855 | array([ ] ][ ]]out[ ]array([ ] ] ] ] ]]when doing matrix computationsyou will do this very oftenlike for example computing the inner matrix product xtx using np dotin [ ]arr np random randn( in [ ]np dot(arr tarrout[ ]array([ ] ] ]]for higher dimensional arraystranspose will accept tuple of axis numbers to permute the ... |
11,856 | universal functionor ufuncis function that performs elementwise operations on data in ndarrays you can think of them as fast vectorized wrappers for simple functions that take one or more scalar values and produce one or more scalar results many ufuncs are simple elementwise transformationslike sqrt or expin [ ]arr np ... |
11,857 | table - unary ufuncs function description absfabs compute the absolute value element-wise for integerfloating pointor complex values use fabs as faster alternative for non-complex-valued data sqrt compute the square root of each element equivalent to arr * square compute the square of each element equivalent to arr * e... |
11,858 | description greatergreater_equallessless_equalequalnot_equal perform element-wise comparisonyielding boolean array equivalent to infix operators logical_andlogical_orlogical_xor compute element-wise truth value of logical operation equivalent to infix operators >>=<<===!|data processing using arrays using numpy arrays ... |
11,859 | out[ ]in [ ]plt title("image plot of $\sqrt{ ^ ^ }for grid of values"out[ ]see figure - here used the matplotlib function imshow to create an image plot from array of function values figure - plot of function evaluated on grid expressing conditional logic as array operations the numpy where function is vectorized versi... |
11,860 | the work is being done in pure pythonsecondlyit will not work with multidimensional arrays with np where you can write this very conciselyin [ ]result np where(condxarryarrin [ ]result out[ ]array( ]the second and third arguments to np where don' need to be arraysone or both of them can be scalars typical use of where ... |
11,861 | where expressionnp where(cond cond np where(cond np where(cond ))in this particular examplewe can also take advantage of the fact that boolean values are treated as or in calculationsso this could alternatively be expressed (though bit more crypticallyas an arithmetic operationresult cond cond -(cond cond mathematical ... |
11,862 | method description sum sum of all the elements in the array or along an axis zero-length arrays have sum mean arithmetic mean zero-length arrays have nan mean stdvar standard deviation and variancerespectivelywith optional degrees of freedom adjustment (default denominator nminmax minimum and maximum argminargmax indic... |
11,863 | out[ ]array([- - - ] multidimensional arrays can have each section of values sorted in-place along an axis by passing the axis number to sortin [ ]arr randn( in [ ]arr out[ ]array([[- - - ] - - ][- - ][- - ] - ]]in [ ]arr sort( in [ ]arr out[ ]array([[- - - ][- - ][- - ][- - ][- ]]the top level method np sort returns s... |
11,864 | dtype='| 'in [ ]ints np array([ ]in [ ]np unique(intsout[ ]array([ ]contrast np unique with the pure python alternativein [ ]sorted(set(names)out[ ]['bob''joe''will'another functionnp in dtests membership of the values in one array in anotherreturning boolean arrayin [ ]values np array([ ]in [ ]np in (values[ ]out[ ]ar... |
11,865 | on disk can then be loaded using np loadin [ ]np load('some_array npy'out[ ]array([ ]you save multiple arrays in zip archive using np savez and passing the arrays as keyword argumentsin [ ]np savez('array_archive npz' =arrb=arrwhen loading an npz fileyou get back dict-like object which loads the individual arrays lazil... |
11,866 | linear algebra linear algebralike matrix multiplicationdecompositionsdeterminantsand other square matrix mathis an important part of any array library unlike some languages like matlabmultiplying two two-dimensional arrays with is an element-wise product instead of matrix dot product as suchthere is function dotboth an... |
11,867 | array([ - - - - - ] ] ] - ] ]]in [ ]qr qr(matin [ ] out[ ]array([- - - - - - ] - ] ]- ] ]]see table - for list of some of the most commonly-used linear algebra functions the scientific python community is hopeful that there may be matrix multiplication infix operator implemented somedayproviding syntactically nicer alt... |
11,868 | normal distribution using normalin [ ]samples np random normal(size=( )in [ ]samples out[ ]array([ ] - - - ][- - - ] - - ]]python' built-in random moduleby contrastonly samples one value at time as you can see from this benchmarknumpy random is well over an order of magnitude faster for generating very large samplesin ... |
11,869 | an illustrative application of utilizing array operations is in the simulation of random walks let' first consider simple random walk starting at with steps of and - occurring with equal probability pure python way to implement single random walk with , steps using the built-in random moduleimport random position walk ... |
11,870 | the walk' trajectoryin [ ]walk min(out[ ]- in [ ]walk max(out[ ] more complicated statistic is the first crossing timethe step at which the random walk reaches particular value here we might want to know how long it took the random walk to get at least steps away from the origin in either direction np abs(walk> gives u... |
11,871 | slightly tricky because not all , of them reach we can check this using the any methodin [ ]hits (np abs(walks> any( in [ ]hits out[ ]array([falsetruefalsefalsetruefalse]dtype=boolin [ ]hits sum(number that hit or - out[ ] we can use this boolean array to select out the rows of walks that actually cross the absolute le... |
11,872 | getting started with pandas pandas will be the primary library of interest throughout much of the rest of the book it contains high-level data structures and manipulation tools designed to make data analysis fast and easy in python pandas is built on top of numpy and makes it easy to use in numpy-centric applications a... |
11,873 | in [ ]import pandas as pd thuswhenever you see pd in codeit' referring to pandas series and dataframe are used so much that find it easier to import them into the local namespace introduction to pandas data structures to get started with pandasyou will need to get comfortable with its two workhorse data structuresserie... |
11,874 | out[ ]index([dbac]dtype=objectcompared with regular numpy arrayyou can use values in the index when selecting single values or set of valuesin [ ]obj [' 'out[ ]- in [ ]obj [' ' in [ ]obj [[' '' '' ']out[ ] - numpy array operationssuch as filtering with boolean arrayscalar multiplicationor applying math functionswill pr... |
11,875 | utah when only passing dictthe index in the resulting series will have the dict' keys in sorted order in [ ]states ['california''ohio''oregon''texas'in [ ]obj series(sdataindex=statesin [ ]obj out[ ]california nan ohio oregon texas in this case values found in sdata were placed in the appropriate locationsbut since no ... |
11,876 | utah nan data alignment features are addressed as separate topic both the series object itself and its index have name attributewhich integrates with other key areas of pandas functionalityin [ ]obj name 'populationin [ ]obj index name 'statein [ ]obj out[ ]state california nan ohio oregon texas namepopulation series' ... |
11,877 | is from dict of equal-length lists or numpy arrays data {'state'['ohio''ohio''ohio''nevada''nevada']'year'[ ]'pop'[ ]frame dataframe(datathe resulting dataframe will have its index assigned automatically as with seriesand the columns are placed in sorted orderin [ ]frame out[ ]pop state ohio ohio ohio nevada nevada yea... |
11,878 | ohio three ohio four nevada five nevada namestate two three four five nameyear note that the returned series have the same index as the dataframeand their name attribute has been appropriately set rows can also be retrieved by position or name by couple of methodssuch as the ix indexing field (much more on this later)i... |
11,879 | two three four five ohio ohio ohio nevada nevada nan - nan - - assigning column that doesn' exist will create new column the del keyword will delete columns as with dictin [ ]frame ['eastern'frame state ='ohioin [ ]frame out[ ]year state one ohio two ohio three ohio four nevada five nevada pop debt eastern nan true - t... |
11,880 | isn' true if an explicit index is specifiedin [ ]dataframe(popindex=[ ]out[ ]nevada ohio nan nan dicts of series are treated much in the same wayin [ ]pdata {'ohio'frame ['ohio'][:- ]'nevada'frame ['nevada'][: ]in [ ]dataframe(pdataout[ ]nevada ohio nan for complete list of things you can pass the dataframe constructor... |
11,881 | type notes ndarray matrix of datapassing optional row and column labels dict of arrayslistsor tuples each sequence becomes column in the dataframe all sequences must be the same length numpy structured/record array treated as the "dict of arrayscase dict of series each value becomes column indexes from each series are ... |
11,882 | structuresin [ ]index pd index(np arange( )in [ ]obj series([ - ]index=indexin [ ]obj index is index out[ ]true table - has list of built-in index classes in the library with some development effortindex can even be subclassed to implement specialized axis indexing functionality many users will not need to know much ab... |
11,883 | method description append concatenate with additional index objectsproducing new index diff compute set difference as an index intersection compute set intersection union compute set union isin compute boolean array indicating whether each value is contained in the passed collection delete compute new index with elemen... |
11,884 | nan in [ ]obj reindex([' '' '' '' '' ']fill_value= out[ ] - for ordered data like time seriesit may be desirable to do some interpolation or filling of values when reindexing the method option allows us to do thisusing method such as ffill which forward fills the valuesin [ ]obj series(['blue''purple''yellow']index=[ ]... |
11,885 | ohio nan texas nan california nan the columns can be reindexed using the columns keywordin [ ]states ['texas''utah''california'in [ ]frame reindex(columns=statesout[ ]texas utah california nan nan nan both can be reindexed in one shotthough interpolation will only apply row-wise (axis )in [ ]frame reindex(index=[' '' '... |
11,886 | dropping one or more entries from an axis is easy if you have an index array or list without those entries as that can require bit of munging and set logicthe drop method will return new object with the indicated value or values deleted from an axisin [ ]obj series(np arange( )index=[' '' '' '' '' ']in [ ]new_obj obj d... |
11,887 | in [ ]obj[[ ]out[ ] in [ ]obj[obj out[ ] slicing with labels behaves differently than normal python slicing in that the endpoint is inclusivein [ ]obj[' ':' 'out[ ] setting using these methods works just as you would expectin [ ]obj[' ':' ' in [ ]obj out[ ] as you've seen aboveindexing into dataframe is for retrieving ... |
11,888 | colorado colorado utah new york this might seem inconsistent to some readersbut this syntax arose out of practicality and nothing more another use case is in indexing with boolean dataframesuch as one produced by scalar comparisonin [ ]data out[ ]one two ohio true true colorado true false utah false false new york fals... |
11,889 | colorado utah new york two three so there are many ways to select and rearrange the data contained in pandas object for dataframethere is short summary of many of them in table - you have number of additional options when working with hierarchical indexes as you'll later see when designing pandasi felt that having to t... |
11,890 | adding these together yieldsin [ ] out[ ] nan nan nan the internal data alignment introduces na values in the indices that don' overlap missing values propagate in arithmetic computations in the case of dataframealignment is performed on both the rows and the columnsin [ ]df dataframe(np arange( reshape(( ))columns=lis... |
11,891 | adding these together results in na values in the locations that don' overlapin [ ]df df out[ ] nan nan nan nan nan nan nan nan using the add method on df pass df and an argument to fill_valuein [ ]df add(df fill_value= out[ ] relatedlywhen reindexing series or dataframeyou can also specify different fill valuein [ ]df... |
11,892 | ]]in [ ]arr[ out[ ]array( in [ ]arr arr[ out[ ]array([ ] ] ]] ]this is referred to as broadcasting and is explained in more detail in operations between dataframe and series are similarin [ ]frame dataframe(np arange( reshape(( ))columns=list('bde')index=['utah''ohio''texas''oregon']in [ ]series frame ix[ in [ ]frame o... |
11,893 | utah ohio texas oregon out[ ]utah ohio texas oregon named in [ ]frame sub(series axis= out[ ] utah - ohio - texas - oregon - the axis number that you pass is the axis to match on in this case we mean to match on the dataframe' row index and broadcast across function application and mapping numpy ufuncs (element-wise ar... |
11,894 | min - max - element-wise python functions can be usedtoo suppose you wanted to compute formatted string from each floating point value in frame you can do this with applymapin [ ]format lambda ' fx in [ ]frame applymap(formatout[ ] utah - - ohio - texas oregon - the reason for the name applymap is that series has map m... |
11,895 | tooin [ ]frame sort_index(axis= ascending=falseout[ ] three one to sort series by its valuesuse its order methodin [ ]obj series([ - ]in [ ]obj order(out[ ] - any missing values are sorted to the end of the series by defaultin [ ]obj series([ np nan np nan- ]in [ ]obj order(out[ ] - nan nan on dataframeyou may want to ... |
11,896 | valid data points in an array it is similar to the indirect sort indices produced by numpy argsortexcept that ties are broken according to rule the rank methods for series and dataframe are the place to lookby default rank breaks ties by assigning each group the mean rankin [ ]obj series([ - ]in [ ]obj rank(out[ ] rank... |
11,897 | method description 'averagedefaultassign the average rank to each entry in the equal group 'minuse the minimum rank for the whole group 'maxuse the maximum rank for the whole group 'firstassign ranks in the order the values appear in the data axis indexes with duplicate values up until now all of the examples 've showe... |
11,898 | - summarizing and computing descriptive statistics pandas objects are equipped with set of common mathematical and statistical methods most of these fall into the category of reductions or summary statisticsmethods that extract single value (like the sum or meanfrom series or series of values from the rows or columns o... |
11,899 | method description axis axis to reduce over for dataframe' rows and for columns skipna exclude missing valuestrue by default level reduce grouped by level if the axis is hierarchically-indexed (multiindexsome methodslike idxmin and idxmaxreturn indirect statistics like the index value where the minimum or maximum value... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.