id
int64
0
25.6k
text
stringlengths
0
4.59k
11,900
method description count number of non-na values describe compute set of summary statistics for series or each dataframe column minmax compute minimum and maximum values argminargmax compute index locations (integersat which minimum or maximum value obtainedrespectively idxminidxmax compute index values at which minimu...
11,901
aapl goog ibm msft date - - - - - - - - the corr method of series computes the correlation of the overlappingnon-naaligned-by-index values in two series relatedlycov computes the covariancein [ ]returns msft corr(returns ibmout[ ] in [ ]returns msft cov(returns ibmout[ ] dataframe' corr and cov methodson the other hand...
11,902
msft - - passing axis= does things row-wise instead in all casesthe data points are aligned by label before computing the correlation unique valuesvalue countsand membership another class of related methods extracts information about the values contained in one-dimensional series to illustrate theseconsider this exampl...
11,903
true true see table - for reference on these methods table - uniquevalue countsand binning methods method description isin compute boolean array indicating whether each series value is contained in the passed sequence of values unique compute array of unique values in seriesreturned in the order observed value_counts r...
11,904
both floating as well as in non-floating point arrays it is just used as sentinel that can be easily detectedin [ ]string_data series(['aardvark''artichoke'np nan'avocado']in [ ]string_data out[ ] aardvark artichoke nan avocado in [ ]string_data isnull(out[ ] false false true false the built-in python none value is als...
11,905
naturallyyou could have computed this yourself by boolean indexingin [ ]data[data notnull()out[ ] with dataframe objectsthese are bit more complex you may want to drop rows or columns which are all na or just those containing any nas dropna by default drops any row containing missing valuein [ ]data dataframe([[ ][ nan...
11,906
out[ ] - nan nan nan nan - nan nan - nan - nan - - - - - - in [ ]df dropna(thresh= out[ ] - - - - - filling in missing data rather than filtering out missing data (and potentially discarding other data along with it)you may want to fill in the "holesin any number of ways for most purposesthe fillna method is the workho...
11,907
- - - - - the same interpolation methods available for reindexing can be used with fillnain [ ]df dataframe(np random randn( )in [ ]df ix[ : nadf ix[ : na in [ ]df out[ ] - nan nan - nan nan nan nan in [ ]df fillna(method='ffill'out[ ] - - - - in [ ]df fillna(method='ffill'limit= out[ ] - - nan - nan - with fillna you ...
11,908
hierarchical indexing is an important feature of pandas enabling you to have multiple (two or moreindex levels on an axis somewhat abstractlyit provides way for you to work with higher dimensional data in lower dimensional form let' start with simple examplecreate series with list of lists or arrays as the indexin [ ]d...
11,909
- - hierarchical indexing plays critical role in reshaping data and group-based operations like forming pivot table for examplethis data could be rearranged into dataframe using its unstack methodin [ ]data unstack(out[ ] - - - - - - nan nan the inverse operation of unstack is stackin [ ]data unstack(stack(out[ ] - - -...
11,910
state color key key ohio green red colorado green with partial column indexing you can similarly select groups of columnsin [ ]frame['ohio'out[ ]color green red key key multiindex can be created by itself and then reusedthe columns in the above dataframe with level names could be created like thismultiindex from_arrays...
11,911
objects if the index is lexicographically sorted starting with the outermost levelthat isthe result of calling sortlevel( or sort_index(summary statistics by level many descriptive and summary statistics on dataframe and series have level option in which you can specify the level you want to sum by on particular axis c...
11,912
columns as the indexin [ ]frame frame set_index([' '' ']in [ ]frame out[ ] one two by default the columns are removed from the dataframethough you can leave them inin [ ]frame set_index([' '' ']drop=falseout[ ] one one one one two two two two two reset_indexon the other handdoes the opposite of set_indexthe hierarchica...
11,913
to generate an errorser series(np arange( )ser[- in this casepandas could "fall backon integer indexingbut there' not safe and general way (that know ofto do this without introducing subtle bugs here we have an index containing but inferring what the user wants (label-based indexing or position-basedis difficult:in [ ]...
11,914
of cases to create panelyou can use dict of dataframe objects or three-dimensional ndarrayimport pandas io data as web pdata pd panel(dict((stkweb get_data_yahoo(stk'''')for stk in ['aapl''goog''msft''dell'])each item (the analogue of columns in dataframein the panel is dataframein [ ]pdata out[ ]dimensions (itemsx (ma...
11,915
an alternate way to represent panel dataespecially for fitting statistical modelsis in "stackeddataframe formin [ ]stacked pdata ix[:''::to_frame(in [ ]stacked out[ ]major minor aapl dell goog msft aapl dell goog msft aapl dell goog msft open high low close volume adj close dataframe has related to_panel methodthe inve...
11,916
data loadingstorageand file formats the tools in this book are of little use if you can' easily import and export data in python ' going to be focused on input and output with pandas objectsthough there are of course numerous tools in other libraries to aid in this process numpyfor examplefeatures low-level but extreme...
11,917
text data into dataframe the options for these functions fall into few categoriesindexingcan treat one or more columns as the returned dataframeand whether to get column names from the filethe useror not at all type inference and data conversionthis includes the user-defined value conversions and custom list of missing...
11,918
in [ ]!cat ch /ex csv , , , ,hello , , , ,world , , , ,foo to read this inyou have couple of options you can allow pandas to assign default column namesor you can specify names yourselfin [ ]pd read_csv('ch /ex csv'header=noneout[ ] hello world foo in [ ]pd read_csv('ch /ex csv'names=[' '' '' '' ''message']out[ ] messa...
11,919
one two value value in some casesa table might not have fixed delimiterusing whitespace or some other pattern to separate fields in these casesyou can pass regular expression as delimiter for read_table consider text file that looks like thisin [ ]list(open('ch /ex txt')out[ ][ \ ''aaa - - - \ ''bbb - \ ''ccc - - - \ '...
11,920
hello world foo handling missing values is an important and frequently nuanced part of the file parsing process missing data is usually either not present (empty stringor marked by some sentinel value by defaultpandas uses set of commonly occurring sentinelssuch as na- #indand nullin [ ]!cat ch /ex csv something, , , ,...
11,921
argument description path string indicating filesystem locationurlor file-like object sep or delimiter character sequence or regular expression to use to split fields in each row header row number to use as column names defaults to (first row)but should be none if there is no header row index_col column numbers or name...
11,922
int index entries to data columnsone non-null values two non-null values three non-null values four non-null values key non-null values dtypesfloat ( )object( if you want to only read out small number of rows (avoiding reading the entire file)specify that with nrowsin [ ]pd read_csv('ch /ex csv'nrows= out[ ]one two thr...
11,923
of an arbitrary size writing data out to text format data can also be exported to delimited format let' consider one of the csv files read abovein [ ]data pd read_csv('ch /ex csv'in [ ]data out[ ]something one two three nan message nan world foo using dataframe' to_csv methodwe can write the data out to comma-separated...
11,924
, , , , , , , series also has to_csv methodin [ ]dates pd date_range(''periods= in [ ]ts series(np arange( )index=datesin [ ]ts to_csv('ch /tseries csv'in [ ]!cat ch /tseries csv : : , : : , : : , : : , : : , : : , : : , with bit of wrangling (no headerfirst column as index)you can read csv version of series with read_...
11,925
open('ch /ex csv'reader csv reader(fiterating through the reader like file yields tuples of values in each like with any quote characters removedin [ ]for line in readerprint line [' '' '' '[' '' '' '[' '' '' '' 'from thereit' up to you to do the wrangling necessary to put the data in the form that you need it for exam...
11,926
description csv quote_nonnumericand csv quote_non (no quotingsee python' documentation for full details defaults to quote_minimal skipinitialspace ignore whitespace after each delimiter default false doublequote how to handle quoting character inside field if trueit is doubled see online documentation for full detail a...
11,927
in [ ]result out[ ]{ 'name' 'wes' 'pet'noneu'places_lived'[ 'united states' 'spain' 'germany'] 'siblings'[{ 'age' 'name' 'scott' 'pet' 'zuko'}{ 'age' 'name' 'katie' 'pet' 'cisco'}]json dumps on the other hand converts python object back to jsonin [ ]asjson json dumps(resulthow you convert json object or list of objects...
11,928
parse the stream with lxml like sofrom lxml html import parse from urllib import urlopen parsed parse(urlopen('doc parsed getroot(using this objectyou can extract all html tags of particular typesuch as table tags containing the data of interest as simple motivating examplesuppose you wanted to get list of every url li...
11,929
''nowfinding the right tables in the document can be matter of trial and errorsome websites make it easier by giving table of interest an id attribute determined that these were the two tables containing the call data and put datarespectivelytables doc findall(//table'calls tables[ puts tables[ each table has header ro...
11,930
in [ ]put_data parse_options_data(putsin [ ]call_data[: out[ ]strike symbol aapl aapl aapl aapl aapl aapl aapl aapl aapl aapl last chg bid ask vol open int / / parsing xml with lxml objectify xml (extensible markup languageis another common structured data format supporting hierarchicalnested data with metadata the fil...
11,931
file with getrootfrom lxml import objectify path 'performance_mnr xmlparsed objectify parse(open(path)root parsed getroot(root indicator return generator yielding each xml element for each recordwe can populate dict of tag names (like ytd_actualto data values (excluding few tags)data [skip_fields ['parent_seq''indicato...
11,932
one of the easiest ways to store data efficiently in binary format is using python' builtin pickle serialization convenientlypandas objects all have save method which writes the data to disk as picklein [ ]frame pd read_csv('ch /ex csv'in [ ]frame out[ ] message hello world foo in [ ]frame save('ch /frame_pickle'you re...
11,933
and some support for out-of-core computations pandas has minimal dict-like hdfstore classwhich uses pytables to store pandas objectsin [ ]store pd hdfstore('mydata 'in [ ]store['obj 'frame in [ ]store['obj _col'frame[' 'in [ ]store out[ ]file pathmydata obj dataframe obj _col series objects contained in the hdf file ca...
11,934
many websites have public apis providing data feeds via json or some other format there are number of ways to access these apis from pythonone easy-to-use method that recommend is the requests package (for the words "python pandason twitterwe can make an http get request like soin [ ]import requests in [ ]url 'in [ ]re...
11,935
'to_user_name'nonewe can then make list of the tweet fields of interest then pass the results list to dataframein [ ]tweet_fields ['created_at''from_user''id''text'in [ ]tweets dataframe(data['results']columns=tweet_fieldsin [ ]tweets out[ ]int index entries to data columnscreated_at non-null values from_user non-null ...
11,936
con execute(querycon commit(theninsert few rows of datadata [('atlanta''georgia' )('tallahassee''florida' )('sacramento''california' )stmt "insert into test values(????)con executemany(stmtdatacon commit(most python sql drivers (pyodbcpsycopg mysqldbpymssqletc return list of tuples when selecting data from tablein [ ]c...
11,937
nosql databases take many different forms some are simple dict-like key-value stores like berkeleydb or tokyo cabinetwhile others are document-basedwith dict-like object being the basic unit of storage 've chosen mongodb (my example started mongodb instance locally on my machineand connect to it on the default port usi...
11,938
data wranglingcleantransformmergereshape much of the programming work in data analysis and modeling is spent on data preparationloadingcleaningtransformingand rearranging sometimes the way that data is stored in files or databases is not the way you need it for data processing application many people choose to do ad ho...
11,939
merge or join operations combine data sets by linking rows using one or more keys these operations are central to relational databases the merge function in pandas is the main entry point for using these algorithms on your data let' start with simple examplein [ ]df dataframe({'key'[' '' '' '' '' '' '' ']'data 'range( ...
11,940
'data 'range( )}in [ ]pd merge(df df left_on='lkey'right_on='rkey'out[ ]data lkey data rkey you probably noticed that the 'cand 'dvalues and associated data are missing from the result by default merge does an 'innerjointhe keys in the result are the intersection other possible options are 'left''right'and 'outerthe ou...
11,941
nan many-to-many joins form the cartesian product of the rows since there were 'brows in the left dataframe and in the right onethere are 'brows in the result the join method only affects the distinct key values appearing in the resultin [ ]pd merge(df df how='inner'out[ ]data key data to merge with multiple keyspass l...
11,942
names while you can address the overlap manually (see the later section on renaming axis labels)merge has suffixes option for specifying strings to append to overlapping names in the left and right dataframe objectsin [ ]pd merge(leftrighton='key 'out[ ]key key _x lval key _y rval bar one one bar one two foo one one fo...
11,943
in some casesthe merge key or keys in dataframe will be found in its index in this caseyou can pass left_index=true or right_index=true (or bothto indicate that the index should be used as the merge keyin [ ]left dataframe({'key'[' '' '' '' '' '' ']'value'range( )}in [ ]right dataframe({'group_val'[ ]}index=[' '' ']in ...
11,944
data key ohio ohio ohio nevada nevada key nevada ohio event event in this caseyou have to indicate multiple columns to merge on as list (pay attention to the handling of duplicate index values)in [ ]pd merge(lefthrighthleft_on=['key ''key ']right_index=trueout[ ]data key key event event nevada ohio ohio ohio ohio in [ ...
11,945
used to combine together many dataframe objects having the same or similar indexes but non-overlapping columns in the prior examplewe could have writtenin [ ]left join(right how='outer'out[ ]ohio nevada missouri alabama nan nan nan nan nan nan in part for legacy reasons (much earlier versions of pandas)dataframe' join ...
11,946
another kind of data combination operation is alternatively referred to as concatenationbindingor stacking numpy has concatenate function for doing this with raw numpy arraysin [ ]arr np arange( reshape(( )in [ ]arr out[ ]array([ ] ] ]]in [ ]np concatenate([arrarr]axis= out[ ]array([ ] ] ]]in the context of pandas obje...
11,947
result will instead be dataframe (axis= is the columns)in [ ]pd concat([ ]axis= out[ ] nan nan nan nan nan nan nan nan nan nan nan nan nan nan in this case there is no overlap on the other axiswhich as you can see is the sorted union (the 'outerjoinof the indexes you can instead intersect them by passing join='inner'in...
11,948
one nan nan two nan nan three nan nan in the case of combining series along axis= the keys become the dataframe column headersin [ ]pd concat([ ]axis= keys=['one''two''three']out[ ]one two three nan nan nan nan nan nan nan nan nan nan nan nan nan nan the same logic extends to dataframe objectsin [ ]df dataframe(np aran...
11,949
the context of the analysisin [ ]df dataframe(np random randn( )columns=[' '' '' '' ']in [ ]df dataframe(np random randn( )columns=[' '' '' ']in [ ]df out[ ] - - - - in [ ]df out[ ] - - in this caseyou can pass ignore_index=truein [ ]pd concat([df df ]ignore_index=trueout[ ] - - - - nan - nan - table - concat function ...
11,950
index=[' '' '' '' '' '' ']in [ ] series(np arange(len( )dtype=np float )index=[' '' '' '' '' '' ']in [ ] [- np nan in [ ] out[ ] nan nan nan in [ ] out[ ] nan in [ ]np where(pd isnull( )baout[ ] nan series has combine_first methodwhich performs the equivalent of this operation plus data alignmentin [ ] [:- combine_firs...
11,951
hierarchical indexing provides consistent way to rearrange data in dataframe there are two primary actionsstackthis "rotatesor pivots from the columns in the data to the rows unstackthis pivots from the rows into the columns 'll illustrate these operations through series of examples consider small dataframe with string...
11,952
three two three unstacking might introduce missing data if all of the values in the level aren' found in each of the subgroupsin [ ] series([ ]index=[' '' '' '' ']in [ ] series([ ]index=[' '' '' ']in [ ]data pd concat([ ]keys=['one''two']in [ ]data unstack(out[ ] one nan two nan nan stacking filters out missing data by...
11,953
three right left right pivoting "longto "wideformat common way to store multiple time series in databases and csv is in so-called long or stacked formatin [ ]ldata[: out[ ]date : : : : : : : : : : : : : : : : : : : : item realgdp infl unemp realgdp infl unemp realgdp infl unemp realgdp value data is frequently stored t...
11,954
: : : : : : : : : : : : : : : : : : : : item realgdp infl unemp realgdp infl unemp realgdp infl unemp realgdp value value - - - - by omitting the last argumentyou obtain dataframe with hierarchical columnsin [ ]pivoted ldata pivot('date''item'in [ ]pivoted[: out[ ]value value item infl realgdp unemp infl realgdp unemp ...
11,955
so far in this we've been concerned with rearranging data filteringcleaningand other tranformations are another class of important operations removing duplicates duplicate rows may be found in dataframe for any number of reasons here is an examplein [ ]data dataframe({' '['one' ['two' ' '[ ]}in [ ]data out[ ] one one o...
11,956
one two duplicated and drop_duplicates by default keep the first observed value combination passing take_last=true will return the last onein [ ]data drop_duplicates([' '' ']take_last=trueout[ ] one one two two transforming data using function or mapping for many data setsyou may wish to perform some transformation bas...
11,957
but here we have small problem in that some of the meats above are capitalized and others are not thuswe also need to convert each value to lower casein [ ]data['animal'data['food'map(str lowermap(meat_to_animalin [ ]data out[ ]food bacon pulled pork bacon pastrami corned beef bacon pastrami honey ham nova lox ounces a...
11,958
values that pandas understandswe can use replaceproducing new seriesin [ ]data replace(- np nanout[ ] nan nan - if you want to replace multiple values at onceyou instead pass list then the substitute valuein [ ]data replace([- - ]np nanout[ ] nan nan nan to use different replacement for each valuepass list of substitut...
11,959
in [ ]data index map(str upperout[ ]array([ohiocoloradonew york]dtype=objectyou can assign to indexmodifying the dataframe in placein [ ]data index data index map(str upperin [ ]data out[ ]one two ohio colorado new york three four if you want to create transformed version of data set without modifying the originala use...
11,960
continuous data is often discretized or otherwised separated into "binsfor analysis suppose you have data about group of people in studyand you want to group them into discrete age bucketsin [ ]ages [ let' divide these into bins of to to to and finally and older to do soyou have to use cuta function in pandasin [ ]bins...
11,961
array([youthyouthyouthyoungadultyouthyouthmiddleagedyoungadultseniormiddleagedmiddleagedyoungadult]dtype=objectlevels ( )index([youthyoungadultmiddleagedsenior]dtype=objectif you pass cut integer number of bins instead of explicit bin edgesit will compute equal-length bins based on the minimum and maximum values in the...
11,962
as these discretization functions are especially useful for quantile and group analysis detecting and filtering outliers filtering or transforming outliers is largely matter of applying array operations consider dataframe with some normally distributed datain [ ]np random seed( in [ ]data dataframe(np random randn( )in...
11,963
in [ ]data describe(out[ ] count mean - std min - - - - - max - - - - - - the ufunc np sign returns an array of and - depending on the sign of the values permutation and random sampling permuting (randomly reorderinga series or the rows in dataframe is easy to do using the numpy random permutation function calling perm...
11,964
in [ ]sampler np random randint( len(bag)size= in [ ]sampler out[ ]array([ ]in [ ]draws bag take(samplerin [ ]draws out[ ]array( - - - ]computing indicator/dummy variables another type of transformation for statistical modeling or machine learning applications is converting categorical variable into "dummyor "indicator...
11,965
in [ ]mnames ['movie_id''title''genres'in [ ]movies pd read_table('ch /movies dat'sep='::'header=nonenames=mnamesin [ ]movies[: out[ ]movie_id title genres toy story ( animation|children' |comedy jumanji ( adventure|children' |fantasy grumpier old men ( comedy|romance waiting to exhale ( comedy|drama father of the brid...
11,966
genre_horror genre_musical genre_mystery genre_romance genre_sci-fi genre_thriller genre_war genre_western name for much larger datathis method of constructing indicator variables with multiple membership is not especially speedy lower-level function leveraging the internals of the dataframe could certainly be written ...
11,967
in many string munging and scripting applicationsbuilt-in string methods are sufficient as an examplea comma-separated string can be broken into pieces with splitin [ ]val ' ,bguidoin [ ]val split(','out[ ][' '' 'guido'split is often combined with strip to trim whitespace (including newlines)in [ ]pieces [ strip(for in...
11,968
out[ ]' :: :guidoin [ ]val replace(','''out[ ]'ab guidoregular expressions can also be used with many of these operations as you'll see below table - python built-in string methods argument description count return the number of non-overlapping occurrences of substring in the string endswithstartswith returns true if s...
11,969
in [ ]text "foo bar\ baz \tquxin [ ]re split('\ +'textout[ ]['foo''bar''baz''qux'when you call re split('\ +'text)the regular expression is first compiledthen its split method is called on the passed text you can compile the regex yourself with re compileforming reusable regex objectin [ ]regex re compile('\ +'in [ ]re...
11,970
in [ ] out[ ]in [ ]text[ start(): end()out[ ]'dave@google comregex match returns noneas it only will match if the pattern occurs at the start of the stringin [ ]print regex match(textnone relatedlysub will return new string with occurrences of the pattern replaced by the new stringin [ ]print regex sub('redacted'textda...
11,971
book' scope to give you flavorone variation on the above email regex gives names to the match groupsregex re compile( ""(? [ - - %+-]+(? [ - - -]+(? [ - ]{ , })"""flags=re ignorecase|re verbosethe match object produced by such regex can produce handy dict with the specified group namesin [ ] regex match('wesm@bright ne...
11,972
has concise methods for string operations that skip na values these are accessed through series' str attributefor examplewe could check whether each email address has 'gmailin it with str containsin [ ]data str contains('gmail'out[ ]dave false rob true steve true wes nan regular expressions can be usedtooalong with any...
11,973
method description cat concatenate strings element-wise with optional delimiter contains return boolean array if each string contains pattern/regex count count occurrences of pattern endswithstartswith equivalent to endswith(patternor startswith(patternfor each element findall compute list of all occurrences of pattern...
11,974
]"nutrients""value" "units"" ""description""protein""group""composition}each food has number of identifying attributes along with two lists of nutrients and portion sizes having the data in this form is not particularly amenable for analysisso we need to do some work to wrangle the data into better form after downloadi...
11,975
we'll take the food namesgroupidand manufacturerin [ ]info_keys ['description''group''id''manufacturer'in [ ]info dataframe(dbcolumns=info_keysin [ ]info[: out[ ]description cheesecaraway cheesecheddar cheeseedam cheesefeta cheesemozzarellapart skim milk group dairy and egg products dairy and egg products dairy and egg...
11,976
in [ ]nutrients out[ ]int index entries to data columnsdescription non-null values group non-null values units non-null values value non-null values id non-null values dtypesfloat ( )int ( )object( noticed thatfor whatever reasonthere are duplicates in this dataframeso it makes things easier to drop themin [ ]nutrients...
11,977
non-null values dtypesfloat ( )int ( )object( with all of this donewe're ready to merge info with nutrientsin [ ]ndata pd merge(nutrientsinfoon='id'how='outer'in [ ]ndata out[ ]int index entries to data columnsnutrient non-null values nutgroup non-null values units non-null values value non-null values id non-null valu...
11,978
the resulting dataframe is bit too large to display in the bookhere is just the 'amino acidsnutrient groupin [ ]max_foods ix['amino acids']['food'out[ ]nutrient alanine gelatinsdry powderunsweetened arginine seedssesame flourlow-fat aspartic acid soy protein isolate cystine seedscottonseed flourlow fat (glandlessglutam...
11,979
11,980
plotting and visualization making plots and static or interactive visualizations is one of the most important tasks in data analysis it may be part of the exploratory processfor examplehelping identify outliersneeded data transformationsor coming up with ideas for models for othersbuilding an interactive visualization ...
11,981
os nativegtkfor most usersthe default backend will be sufficient pylab mode also imports large set of modules and functions into ipython to provide more matlab-like interface you can test that everything is working by making simple plotplot(np arange( )if everything is set up righta new window should pop up with line p...
11,982
ure has number of optionsnotably figsize will guarantee the figure has certain size and aspect ratio if saved to disk figures in matplotlib also support numbering scheme (for exampleplt figure( )that mimics matlab you can get reference to the active figure using plt gcf(you can' make plot with blank figure you have to ...
11,983
figure - figure after additional plots in [ ] ax hist(randn( )bins= color=' 'alpha= in [ ]ax scatter(np arange( )np arange( randn( )you can find comprehensive catalogue of plot types in the matplotlib documentation since creating figure with multiple subplots according to particular layout is such common taskthere is c...
11,984
in [ ]axes out[ ]array([[axes( , ; )axes( , ; )axes( , ; )][axes( , ; )axes( , ; )axes( , ; )]]dtype=objectthis is very useful as the axes array can be easily indexed like two-dimensional arrayfor exampleaxes[ you can also indicate that subplots should have the same or axis using sharex and shareyrespectively this is e...
11,985
you may notice that the axis labels overlap matplotlib doesn' check whether the labels overlapso in case like this you would need to fix the labels yourself by specifying explicit tick locations and tick labels more on this in the coming sections colorsmarkersand line styles matplotlib' main plot function accepts array...
11,986
this could also have been written more explicitly asplot(randn( cumsum()color=' 'linestyle='dashed'marker=' 'for line plotsyou will notice that subsequent points are linearly interpolated by default this can be altered with the drawstyle optionin [ ]data randn( cumsum(in [ ]plt plot(data' --'label='default'out[ ][in [ ...
11,987
called with parameters sets the parameter value so plt xlim([ ])sets the axis range to to all such methods act on the active or most recently-created axessubplot each of them corresponds to two methods on the subplot object itselfin the case of xlim these are ax get_xlim and ax set_xlim prefer to use the subplot instan...
11,988
in [ ]ax set_title('my first matplotlib plot'out[ ]in [ ]ax set_xlabel('stages'see figure - for the resulting figure modifying the axis consists of the same processsubstituting for in the above figure - simple plot for illustrating xticks brief matplotlib api primer www it-ebooks info
11,989
adding legends legends are another critical element for identifying plot elements there are couple of ways to add one the easiest is to pass the label argument when adding each piece of the plotin [ ]fig plt figure()ax fig add_subplot( in [ ]ax plot(randn( cumsum()' 'label='one'out[ ][in [ ]ax plot(randn( cumsum()' --'...
11,990
text draws text at given coordinates (xyon the plot with optional custom stylingax text(xy'hello world!'family='monospace'fontsize= annotations can draw both text and arrows arranged appropriately as an examplelet' plot the closing & index price since (obtained from yahoofinanceand annotate it with some of the importan...
11,991
ax add_patch(circax add_patch(pgonfigure - important dates in - financial crisis figure - figure composed from different patches if you look at the implementation of many familiar plot typesyou will see that they are assembled from patches plotting and visualization www it-ebooks info
11,992
the active figure can be saved to file using plt savefig this method is equivalent to the figure object' savefig instance method for exampleto save an svg version of figureyou need only typeplt savefig('figpath svg'the file type is inferred from the file extension so if you used pdf instead you would get pdf there are ...
11,993
'axes''xtick''ytick''grid''legendor many others after that can follow sequence of keyword arguments indicating the new parameters an easy way to write down the options in your program is as dictfont_options {'family'monospace''weight'bold''size'small'plt rc('font'**font_optionsfor more extensive customization and to se...
11,994
table - for full listing of plot options 'll comment on few more of them throughout this section and leave the rest to you to explore most of pandas' plotting methods accept an optional ax parameterwhich can be matplotlib subplot object this gives you more flexible placement of subplots in grid layout there will be mor...
11,995
argument description kind can be 'line''bar''barh''kdelogy use logarithmic scaling on the axis use_index use the object index for tick labels rot rotation of tick labels ( through xticks values to use for axis ticks yticks values to use for axis ticks xlim axis limits ( [ ]ylim axis limits grid display axis grid (on by...
11,996
description title plot title as string legend add subplot legend (true by defaultsort_columns plot columns in alphabetical orderby default uses existing column order for time series plottingsee bar plots making bar plots instead of line plots is simple as passing kind='bar(for vertical barsor kind='barh(for horizontal ...
11,997
note that the name "genuson the dataframe' columns is used to title the legend stacked bar plots are created from dataframe by passing stacked=trueresulting in the value in each row being stacked together (see figure - )in [ ]df plot(kind='barh'stacked=truealpha= useful recipe for bar plots (as seen in an earlier is to...
11,998
in [ ]party_counts party_counts ix[: : figure - dataframe bar plot example figure - dataframe stacked bar plot example thennormalize so that each row sums to ( have to cast to float to avoid integer division issues on python and make the plot (see figure - )normalize to sum to in [ ]party_pcts party_counts div(party_co...
11,999
out[ ]size day fri sat sun thur in [ ]party_pcts plot(kind='bar'stacked=truefigure - fraction of parties by size on each day so you can see that party sizes appear to increase on the weekend in this data set histograms and density plots histogramwith which you may be well-acquaintedis kind of bar plot that gives discre...