id
int64
0
25.6k
text
stringlengths
0
4.59k
12,000
related plot type is density plotwhich is formed by computing an estimate of continuous probability distribution that might have generated the observed data usual procedure is to approximate this distribution as mixture of kernelsthat issimpler distributions like the normal (gaussiandistribution thusdensity plots are a...
12,001
figure - normalized histogram of normal mixture with density estimate making these kinds of plots to give an examplei load the macrodata dataset from the statsmodels projectselect few variablesthen compute log differencesin [ ]macro pd read_csv('ch /macrodata csv'in [ ]data macro[['cpi'' ''tbilrate''unemp']in [ ]trans_...
12,002
out[ ]cpi tbilrate - - - - - - unemp it' easy to plot simple scatter plot using plt scatter (see figure - )in [ ]plt scatter(trans_data[' ']trans_data['unemp']out[ ]in [ ]plt title('changes in log % vs log % (' ''unemp')figure - simple scatter plot in exploratory data analysis it' helpful to be able to look at all the ...
12,003
the data collected during the haiti earthquake crisis and aftermathand 'll show you how prepared the data for analysis and visualization using pandas and other tools we have looked at thus far after downloading the csv file from the above linkwe can load it into dataframe using read_csvin [ ]data pd read_csv('ch /haiti...
12,004
: : : : : : : : : : - - - - - - - the category field contains comma-separated list of codes indicating the type of messagein [ ]data['category'][: out[ ] urgences emergency public health urgences emergency urgences logistiques urgences logistiques vital lines autre urgences emergency urgences emergency communication li...
12,005
def get_all_categories(cat_series)cat_sets (set(to_cat_list( )for in cat_seriesreturn sorted(set union(*cat_sets)def get_english(cat)codenames cat split('if '|in namesnames names split(')[ return codenames strip(you can test out that the get_english function does what you expectin [ ]get_english(' urgences logistiques ...
12,006
non-null values non-null values dtypesfloat ( as you recallthe trick is then to set the appropriate entries of each row to lastly joining this with datafor rowcat in zip(data indexdata category)codes get_code(to_cat_list(cat)dummy_frame ix[rowcodes data data join(dummy_frame add_prefix('category_')data finally now has ...
12,007
of report categories for each categoryi filter down the data set to the coordinates labeled by that categoryplot basemap on the appropriate subplottransform the coordinatesthen plot the points using the basemap' plot methodfigaxes plt subplots(nrows= ncols= figsize=( )fig subplots_adjust(hspace= wspace= to_plot [' '' '...
12,008
shapefile_path 'ch /portauprince_roads/portauprince_roadsm readshapefile(shapefile_path'roads'after little more trial and error with the latitude and longitude boundariesi was able to make figure - for the "food shortagecategory python visualization tool ecosystem as is common with open sourcethere are plethora of opti...
12,009
chaco (with matplotlibchaco has much better support for interacting with plot elements and rendering is very fastmaking it good choice for building interactive gui applications figure - chaco example plot mayavi the mayavi projectdeveloped by prabhu ramachandrangael varoquauxand othersis graphics toolkit built on the o...
12,010
toward web-based technologies and away from desktop graphics 'll say few more words about this in the next section the future of visualization toolsvisualizations built on web technologies (that isjavascript-basedappear to be the inevitable future doubtlessly you have used many different kinds of static or interactive ...
12,011
12,012
data aggregation and group operations categorizing data set and applying function to each groupwhether an aggregation or transformationis often critical component of data analysis workflow after loadingmergingand preparing data seta familiar task is to compute group statistics or possibly pivot tables for reporting or ...
12,013
to as resampling in this book and will receive separate treatment in groupby mechanics hadley wickhaman author of many popular packages for the programming languagecoined the term split-apply-combine for talking about group operationsand think that' good description of the process in the first stage of the processdata ...
12,014
grouped and the group names function to be invoked on the axis index or the individual labels in the index note that the latter three methods are all just shortcuts for producing an array of values to be used to split up the object don' worry if this all seems very abstract throughout this will give many examples of al...
12,015
out[ ]key key one two one - two - in this casewe grouped the data using two keysand the resulting series now has hierarchical index consisting of the unique pairs of keys observedin [ ]means unstack(out[ ]key one two key - - in these examplesthe group keys are all seriesthough they could be any arrays of the right leng...
12,016
see soon regardless of the objective in using groupbya generally useful groupby method is size which return series containing group sizesin [ ]df groupby(['key ''key ']size(out[ ]key key one two one two as of this writingany missing values in group key will be excluded from the result it' possible (andin factquite like...
12,017
one two data data key key - two of courseyou can choose to do whatever you want with the pieces of data recipe you may find useful is computing dict of the data pieces as one-linerin [ ]pieces dict(list(df groupby('key '))in [ ]pieces[' 'out[ ]data data key key - one - two by default groupby groups on axis= but you can...
12,018
examplein the above data setto compute means for just the data column and get the result as dataframewe could writein [ ]df groupby(['key ''key '])[['data ']mean(out[ ]data key key one two one two the object returned by this indexing operation is grouped dataframe if list or array is passed and grouped series is just s...
12,019
we can just pass the dictin [ ]by_column people groupby(mappingaxis= in [ ]by_column sum(out[ ]blue red joe steve - wes - - jim travis - - the same functionality holds for serieswhich can be viewed as fixed size mapping when used series as group keys in the above examplespandas doesin factinspect each series to ensure ...
12,020
- - - - - mixing functions with arraysdictsor series is not problem as everything gets converted to arrays internallyin [ ]key_list ['one''one''one''two''two'in [ ]people groupby([lenkey_list]min(out[ ] one - - - - two one - - - two - - - - - grouping by index levels final convenience for hierarchically-indexed data se...
12,021
object for exampleas you recall quantile computes sample quantiles of series or dataframe' columns in [ ]df out[ ]data - - - data key key one two one two one in [ ]grouped df groupby('key 'in [ ]grouped['data 'quantile( out[ ]key - while quantile is not explicitly implemented for groupbyit is series method and thus ava...
12,022
max count mean - std min - - - - max - will explain in more detail what has happened here in the next major section on groupwise operations and transformations you may notice that custom aggregation functions are much slower than the optimized functions found in table - this is because there is significant overhead (fu...
12,023
male male female male no no no no sun sun sun sun dinner dinner dinner dinner column-wise and multiple function application as you've seen aboveaggregating series or all of the columns of dataframe is matter of using aggregate with the desired function or calling method like mean or std howeveryou may want to aggregate...
12,024
no yes with dataframeyou have more options as you can specify list of functions to apply to all of the columns or different functions per column to startsuppose we wanted to compute the same three statistics for the tip_pct and total_bill columnsin [ ]functions ['count''mean''max'in [ ]result grouped['tip_pct''total_bi...
12,025
yes male no yes in [ ]grouped agg({'tip_pct['min''max''mean''std']'size'sum'}out[ ]tip_pct size min max mean std sum sex smoker female no yes male no yes dataframe will have hierarchical columns only if multiple functions are applied to at least one column returning aggregated data in "unindexedform in all of the examp...
12,026
out[ ]data - - - data key key one two one two one in [ ] _means df groupby('key 'mean(add_prefix('mean_'in [ ] _means out[ ]mean_data mean_data key - in [ ]pd merge(dfk _meansleft_on='key 'right_index=trueout[ ]data data key key mean_data mean_data - one two one - one - - two - this worksbut is somewhat inflexible you ...
12,027
in [ ]demeaned out[ ] joe - steve - - - wes - nan nan - - jim - - travis - - - - you can check that demeaned now has zero group meansin [ ]demeaned groupby(keymean(out[ ] one - two - as you'll see in the next sectiongroup demeaning can be achieved using apply also applygeneral split-apply-combine like aggregatetransfor...
12,028
yes male male female male male female male female female male no thur lunch no sun dinner no sun dinner no thur lunch no sat dinner yes sat dinner yes sun dinner yes sat dinner yes sun dinner yes sun dinner what has happened herethe top function is called on each piece of the dataframethen the results are glued togethe...
12,029
count mean std min max in [ ]result unstack('smoker'out[ ]smoker no yes count mean std min max inside groupbywhen you invoke method like describeit is actually just shortcut forf lambda xx describe(grouped apply(fsuppressing the group keys in the examples aboveyou see that the resulting object has hierarchical index fo...
12,030
bucket categorization using cutin [ ]frame dataframe({'data 'np random randn( )'data 'np random randn( )}in [ ]factor pd cut(frame data in [ ]factor[: out[ ]categoricalarray([(- ](- - ](- ]( ](- ]( ](- ](- ]( ]( ]]dtype=objectlevels ( )index([(- - ](- ]( ]( ]]dtype=objectthe factor object returned by cut can be passed ...
12,031
when cleaning up missing datain some cases you will filter out data observations using dropnabut in others you may want to impute (fill inthe na values using fixed value or some value derived from the data fillna is the right tool to usefor example here fill in na values with the meanin [ ] series(np random randn( )in ...
12,032
west - we can fill the na values using the group means like soin [ ]fill_mean lambda gg fillna( mean()in [ ]data groupby(group_keyapply(fill_meanout[ ]ohio new york - vermont - florida - oregon nevada california idaho in another caseyou might have pre-defined fill values in your code that vary by group since the groups...
12,033
the ones used in blackjack and other games (to keep things simplei just let the ace be )in [ ]deck[: out[ ]ah jh kh qh nowbased on what said abovedrawing hand of cards from the desk could be written asin [ ]def draw(deckn= )return deck take(np random permutation(len(deck))[: ]in [ ]draw(deckout[ ]ad kc suppose you want...
12,034
ks examplegroup weighted average and correlation under the split-apply-combine paradigm of groupbyoperations between columns in dataframe or two seriessuch group weighted averagebecome routine affair as an exampletake this dataset containing group keysvaluesand some weightsin [ ]df dataframe({'category'[' '' '' '' '' '...
12,035
out[ ]aapl msft xom spx one task of interest might be to compute dataframe consisting of the yearly correlations of daily returns (computed from percent changeswith spx here is one way to do itin [ ]rets close_px pct_change(dropna(in [ ]spx_corr lambda xx corrwith( ['spx']in [ ]by_year rets groupby(lambda xx yearin [ ]...
12,036
def regress(datayvarxvars) data[yvarx data[xvarsx['intercept' result sm ols(yxfit(return result params nowto run yearly linear regression of aapl on spx returnsi executein [ ]by_year apply(regress'aapl'['spx']out[ ]spx intercept - pivot tables and cross-tabulation pivot table is data summarization tool frequently found...
12,037
sex day female fri sat sun thur male fri sat sun thur tip_pct no yes size no yes this table could be augmented to include partial totals by passing margins=true this has the effect of adding all row and column labelswith corresponding values being the group statistics for all the data within single tier in this below e...
12,038
no yes female no yes male no yes male lunch see table - for summary of pivot_table methods table - pivot_table options function name description values column name or names to aggregate by default aggregates all numeric columns rows column names or other group keys to group on the rows of the resulting pivot table cols...
12,039
arrays as in the tips datain [ ]pd crosstab([tips timetips day]tips smokermargins=trueout[ ]smoker no yes all time day dinner fri sat sun thur lunch fri thur all example federal election commission database the us federal election commission publishes data on contributions to political campaigns this includes contribut...
12,040
cand_nm contbr_nm contbr_city contbr_st contbr_zip contbr_employer contbr_occupation contb_receipt_amt contb_receipt_dt receipt_desc memo_cd memo_text form_tp file_num name obamabarack ellmanira tempe az arizona state university professor -dec- nan nan nan sa you can probably think of many ways to start slicing and dic...
12,041
'santorumrick''republican'nowusing this mapping and the map method on series objectsyou can compute an array of political parties from the candidate namesin [ ]fec cand_nm[ : out[ ] obamabarack obamabarack obamabarack obamabarack obamabarack namecand_nm in [ ]fec cand_nm[ : map(partiesout[ ] democrat democrat democrat ...
12,042
out[ ]retired information requested attorney homemaker physician information requested per best efforts engineer teacher consultant professor you will notice by looking at the occupations that many refer to the same basic job typeor there are several variants of the same thing here is code snippet illustrates technique...
12,043
ceo consultant engineer executive homemaker investor lawyer manager not provided owner physician president professor real estate retired self-employed it can be easier to look at this data graphically as bar plot ('barhmeans horizontal bar plotsee figure - )in [ ]over_ mm plot(kind='barh'figure - total donations by par...
12,044
in [ ]grouped fec_mrbo groupby('cand_nm'in [ ]grouped apply(get_top_amounts'contbr_occupation' = out[ ]cand_nm contbr_occupation obamabarack retired attorney not provided homemaker physician lawyer consultant romneymitt retired not provided homemaker attorney president executive namecontb_receipt_amt in [ ]grouped appl...
12,045
in [ ]labels out[ ]categorical:contb_receipt_amt array([( ]( ]( ]( ]( ]( ]]dtype=objectlevels ( )array([( ]( ]( ]( ]( ]( ]( ]( ]]dtype=objectwe can then group the data for obama and romney by name and bin label to get histogram by donation sizein [ ]grouped fec_mrbo groupby(['cand_nm'labels]in [ ]grouped size(unstack( ...
12,046
( ( ( ( nan nan in [ ]normed_sums[:- plot(kind='barh'stacked=truei excluded the two largest bins as these are not donations by individuals see figure - for the resulting figure figure - percentage of total donations received by candidates for each donation size there are of course many refinements and improvements of t...
12,047
al ar az ca co ct dc de fl if you divide each row by the total contribution amountyou get the relative percentage of total donations by state for each candidatein [ ]percent totals div(totals sum( )axis= in [ ]percent[: out[ ]cand_nm obamabarack contbr_st ak al ar az ca co ct dc de fl romneymitt thought it would be int...
12,048
lon_ =(urlon lllon lat_ =(urlat lllat llcrnrlat=lllaturcrnrlat=urlatllcrnrlon=lllonurcrnrlon=urlonresolution=' ' drawcoastlines( drawcountries(shp shapefile(/states/statesp 'dbf dbflib open(/states/statesp 'for npoly in range(shp info()[ ])draw colored polygons on the map shpsegs [shp_object shp read_object(npolyverts ...
12,049
data aggregation and group operations www it-ebooks info
12,050
time series time series data is an important form of structured data in many different fieldssuch as financeeconomicsecologyneuroscienceor physics anything that is observed or measured at many points in time forms time series many time series are fixed frequencywhich is to say that data points occur at regular interval...
12,051
this were derived from the now defunct scikits timeseries library date and time data types and tools the python standard library includes data types for date and time dataas well as calendar-related functionality the datetimetimeand calendar modules are the main places to start the datetime datetime typeor simply datet...
12,052
type description date store calendar date (yearmonthdayusing the gregorian calendar time store time of day as hoursminutessecondsand microseconds datetime stores both date and time timedelta represents the difference between two datetime values (as dayssecondsand microsecondsconverting between string and datetime datet...
12,053
axis index or column in dataframe the to_datetime method parses many different kinds of date representations standard date formats like iso can be parsed very quickly in [ ]datestrs out[ ][''''in [ ]pd to_datetime(datestrsout[ ] : : : : length freqnonetimezonenone it also handles values that should be considered missin...
12,054
description % week number of the year [ sunday is considered the first day of the weekand days before the first sunday of the year are "week % week number of the year [ monday is considered the first day of the weekand days before the first monday of the year are "week % utc time zone offset as +hhmm or -hhmmempty if t...
12,055
- - under the hoodthese datetime objects have been put in datetimeindexand the variable ts is now of type timeseriesin [ ]type(tsout[ ]pandas core series timeseries in [ ]ts index out[ ] : : : : length freqnonetimezonenone it' not necessary to use the timeseries constructor explicitlywhen creating series with datetimei...
12,056
in [ ]ts[stampout[ ]- as convenienceyou can also pass string that is interpretable as datein [ ]ts[''out[ ]- in [ ]ts[' 'out[ ]- for longer time seriesa year or only year and month can be passed to easily select slices of datain [ ]longer_ts series(np random randn( )index=pd date_range(''periods= )in [ ]longer_ts out[ ...
12,057
- - - - - - as before you can pass either string datedatetimeor timestamp remember that slicing in this manner produces views on the source time series just like slicing numpy arrays there is an equivalent instance method truncate which slices timeseries between two datesin [ ]ts truncate(after=''out[ ] - - all of the ...
12,058
out[ ]false indexing into this time series will now either produce scalar values or slices depending on whether timestamp is duplicatedin [ ]dup_ts[''not duplicated out[ ] in [ ]dup_ts[''duplicated out[ ] suppose you wanted to aggregate the data having non-unique timestamps one way to do this is to use groupby and pass...
12,059
while used it previously without explanationyou may have guessed that pan das date_range is responsible for generating datetimeindex with an indicated length according to particular frequencyin [ ]index pd date_range(''''in [ ]index out[ ] : : : : length freqdtimezonenone by defaultdate_range generates daily timestamps...
12,060
length freqdtimezonenone frequencies and date offsets frequencies in pandas are composed of base frequency and multiplier base frequencies are typically referred to by string aliaslike 'mfor monthly or 'hfor hourly for each base frequencythere is an object defined generally referred to as date offset for examplehourly ...
12,061
logic not available in pandasthough the full details of that are outside the scope of this book table - base time series frequencies alias offset type description day calendar daily businessday business daily hour hourly or min minute minutely second secondly or ms milli millisecond ( / th of secondu micro microsecond ...
12,062
one useful frequency class is "week of month"starting with wom this enables you to get dates like the third friday of each monthin [ ]rng pd date_range(''''freq='wom- fri'in [ ]list(rngout[ ][traders of us equity options will recognize these dates as the standard dates of monthly expiry shifting (leading and laggingdat...
12,063
lag the datain [ ]ts shift( freq=' 'out[ ] in [ ]ts shift( freq=' 'out[ ] in [ ]ts shift( freq=' 'out[ ] : : : : : : : : shifting dates with offsets the pandas date offsets can also be used with datetime or timestamp objectsin [ ]from pandas tseries offsets import daymonthend in [ ]now datetime( in [ ]now day(out[ ]dat...
12,064
- of coursean easier and faster way to do this is using resample (much more on this later)in [ ]ts resample(' 'how='mean'out[ ]- - freqm time zone handling working with time zones is generally considered one of the most unpleasant parts of time series manipulation in particulardaylight savings time (dsttransitions are ...
12,065
by defaulttime series in pandas are time zone naive consider the following time seriesrng pd date_range( : 'periods= freq=' 'ts series(np random randn(len(rng))index=rngthe index' tz field is nonein [ ]print(ts index tznone date ranges can be generated with time zone setin [ ]pd date_range( : 'periods= freq=' 'tz='utc'...
12,066
out[ ] : : + : : : + : : : + : : : + : - : : + : : : + : freqd in [ ]ts_eastern tz_convert('europe/berlin'out[ ] : : + : : : + : : : + : : : + : - : : + : : : + : freqd tz_localize and tz_convert are also instance methods on datetimeindexin [ ]ts index tz_localize('asia/shanghai'out[ ] : : : : length freqdtimezoneasia/...
12,067
out[ ] in [ ]stamp_utc tz_convert('us/eastern'value out[ ] when performing time arithmetic using pandas' dateoffset objectsdaylight savings time transitions are respected where possible minutes before dst transition in [ ]from pandas tseries offsets import hour in [ ]stamp pd timestamp( : 'tz='us/eastern'in [ ]stamp ou...
12,068
in [ ]result ts ts in [ ]result index out[ ] : : : : length freqbtimezoneutc periods and period arithmetic periods represent time spanslike daysmonthsquartersor years the period class represents this data typerequiring string or integer and frequency from the above tablein [ ] pd period( freq=' -dec'in [ ] out[ ]period...
12,069
freqm if you have an array of stringsyou can also appeal to the periodindex class itselfin [ ]values [' '' '' 'in [ ]index pd periodindex(valuesfreq=' -dec'in [ ]index out[ ]freqq-dec [ length period frequency conversion periods and periodindex objects can be converted to another frequency using their asfreq method as ...
12,070
- - freqa-dec in [ ]ts asfreq(' 'how='start'out[ ] - - - - - - freqm in [ ]ts asfreq(' 'how='end'out[ ]- - freqb figure - period frequency conversion illustration quarterly period frequencies quarterly data is standard in accountingfinanceand other fields much quarterly data is reported relative to fiscal year endtypic...
12,071
at pm on the nd to last business day of the quarteryou could doin [ ] pm ( asfreq(' '' ' asfreq(' '' ' in [ ] pm out[ ]period( : '' 'in [ ] pm to_timestamp(out[ ]figure - different quarterly frequency conventions generating quarterly ranges works as you would expect using period_range arithmetic is identicaltooin [ ]rn...
12,072
series and dataframe objects indexed by timestamps can be converted to periods using the to_period methodin [ ]rng pd date_range(''periods= freq=' 'in [ ]ts series(randn( )index=rngin [ ]pts ts to_period(in [ ]ts out[ ]- - freqm in [ ]pts out[ ] - - - - - freqm since periods always refer to non-overlapping timespansa t...
12,073
fixed frequency data sets are sometimes stored with timespan information spread across multiple columns for examplein this macroeconomic data setthe year and quarter are in different columnsin [ ]data pd read_csv('ch /macrodata csv'in [ ]data year out[ ] nameyearlength in [ ]data quarter out[ ] namequarterlength by pas...
12,074
on wednesdayto -fri is neither upsampling nor downstampling pandas objects are equipped with resample methodwhich is the workhorse function for all frequency conversionin [ ]rng pd date_range(''periods= freq=' 'in [ ]ts series(randn(len(rng))index=rngin [ ]ts resample(' 'how='mean'out[ ] freqm in [ ]ts resample(' 'how=...
12,075
description kind=none aggregate to periods ('period'or timestamps ('timestamp')defaults to kind of index the time series has convention=none when resampling periodsthe convention ('startor 'end'for converting the low frequency period to high frequency defaults to 'enddownsampling aggregating data to regularlower freque...
12,076
right bin edge is inclusiveso the : value is included in the : to : interval passing closed='leftchanges the interval to be closed on the leftin [ ]ts resample(' min'how='sum'closed='left'out[ ] : : : : : : freq as you can seethe resulting time series is labeled by the timestamps from the right side of each bin by pass...
12,077
without the loffset open-high-low-close (ohlcresampling in financean ubiquitous way to aggregate time series is to compute four values for each bucketthe first (open)last (close)maximum (high)and minimal (lowvalues by passing how='ohlcyou will obtain dataframe having columns containing these four aggregateswhich are ef...
12,078
out[ ]colorado texas new york ohio - - - - - when resampling this to daily frequencyby default missing values are introducedin [ ]df_daily frame resample(' 'in [ ]df_daily out[ ]colorado texas new york ohio - - nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan - - - suppose...
12,079
out[ ]colorado texas new york ohio - - - - - resampling with periods resampling data indexed by periods is reasonably straightforward and works as you would hopein [ ]frame dataframe(np random randn( )index=pd period_range(' - '' - 'freq=' ')columns=['colorado''texas''new york''ohio']in [ ]frame[: out[ ]colorado texas ...
12,080
more rigidin downsamplingthe target frequency must be subperiod of the source frequency in upsamplingthe target frequency must be superperiod of the source frequency if these rules are not satisfiedan exception will be raised this mainly affects the quarterlyannualand weekly frequenciesfor examplethe timespans defined ...
12,081
figure - stock prices in in [ ]close_px['aapl'ix[' - ':' - 'plot(quarterly frequency data is also more nicely formatted with quarterly markerssomething that would be quite bit more work to do by hand see figure - in [ ]appl_q close_px['aapl'resample(' -dec'fill_method='ffill'in [ ]appl_q ix[' ':plot( last feature of ti...
12,082
figure - apple quarterly price - caying weights call these moving window functionseven though it includes functions without fixed-length window like exponentially-weighted moving average like other statistical functionsthese also automatically exclude missing data rolling_mean is one of the simplest such functions it t...
12,083
in [ ]appl_std [ : out[ ]nan nan nan nan freqb in [ ]appl_std plot(figure - apple price with -day ma figure - apple -day daily return standard deviation to compute an expanding window meanyou can see that an expanding window is just special case where the window is the length of the time seriesbut only one or more peri...
12,084
in [ ]expanding_mean lambda xrolling_mean(xlen( )min_periods= calling rolling_mean and friends on dataframe applies the transformation to each column (see figure - )in [ ]pd rolling_mean(close_px plot(logy=truefigure - stocks prices -day ma (log -axissee table - for listing of related functions in pandas table - moving...
12,085
implementation of nan-friendly moving window functions and may be worth looking at depending on your application exponentially-weighted functions an alternative to using static window size with equally-weighted observations is to specify constant decay factor to give more weight to more recent observations in mathemati...
12,086
figure - six-month aapl return correlation to & suppose you wanted to compute the correlation of the & index with many stocks at once writing loop and creating new dataframe would be easy but maybe get repetitiveso if you pass timeseries and dataframea function like rolling_corr will compute the correlation of the time...
12,087
figure - percentile rank of aapl return over year window user-defined moving window functions the rolling_apply function provides means to apply an array function of your own devising over moving window the only requirement is that the function produce single value ( reductionfrom each piece of the array for examplewhi...
12,088
timestamps and periods are represented as -bit integers using numpy' date time dtype this means that for each data pointthere is an associated bytes of memory per timestamp thusa time series with million float data points has memory footprint of approximately megabytes since pandas makes every effort to share indexes a...
12,089
in [ ]%timeit ts resample(' 'how='ohlc' loopsbest of ms per loop it' possible that by the time you read thisthe performance of these algorithms may be even further improved as an examplethere are currently no optimizations for conversions between regular frequenciesbut that would be fairly straightforward to do time se...
12,090
financial and economic data applications the use of python in the financial industry has been increasing rapidly since led largely by the maturation of libraries (like numpy and pandasand the availability of skilled python programmers institutions have found that python is well-suited both as an interactive analysis en...
12,091
one of the most time-consuming issues in working with financial data is the so-called data alignment problem two related time series may have indexes that don' line up perfectlyor two dataframe objects might have columns or row labels that don' match users of matlabrand other matrix-programming languages often invest s...
12,092
out[ ]aapl jnj spx nan xom in [ ]vwap dropna(out[ ]aapl jnj xom since spx wasn' found in volumeyou can choose to explicitly discard that at any point should you wish to align by handyou can use dataframe' align methodwhich returns tuple of reindexed versions of the two objectsin [ ]prices align(volumejoin='inner'out[ ]...
12,093
economic time series are often of annualquarterlymonthlydailyor some other more specialized frequency some are completely irregularfor exampleearnings revisions for stock may arrive at any time the two main tools for frequency conversion and realignment are the resample and reindex methods resample converts data to fix...
12,094
freqb - in practiceupsampling lower frequency data to higherregular frequency is fine solutionbut in the more general irregular time series case it may be poor fit consider an irregularly sampled time series from the same general time periodin [ ]dates pd datetimeindex(['''''''''''']in [ ]ts series(np random randn( )in...
12,095
index=pd period_range(' 'periods= freq=' -dec')in [ ]gdp out[ ] freqq-sep in [ ]infl out[ ] freqa-dec unlike time series with timestampsoperations between different-frequency time series indexed by periods are not possible without explicit conversions in this caseif we know that infl values were observed at the end of ...
12,096
in [ ]ts series(np arange(len(rng)dtype=float)index=rngin [ ]ts out[ ] : : : : : : : : : : : : : : : : length indexing with python datetime time object will extract values at those timesin [ ]from datetime import time in [ ]ts[time( )out[ ] : : : : : : : : under the hoodthis uses an instance method at_time (available o...
12,097
in [ ]irr_ts[indexernp nan in [ ]irr_ts[ : ': : 'out[ ] : : : : nan : : : : : : nan : : : : nan : : nan : : nan : : nan : : nan by passing an array of timestamps to the asof methodyou will obtain an array of the last valid (non-navalues at or before each timestamp so we construct date range at am for each day and pass ...
12,098
columns=[' '' '' ']index=pd date_range(''periods= )in [ ]spliced pd concat([data ix[:'']data ix['':]]in [ ]spliced out[ ] suppose in similar example that data was missing time series present in data in [ ]data dataframe(np ones(( )dtype=float columns=[' '' '' '' ']index=pd date_range(''periods= )in [ ]spliced pd concat...
12,099
in [ ]spliced out[ ] nan to replace the data for subset of symbolsyou can use any of the above techniquesbut sometimes it' simpler to just set the columns directly with dataframe indexingin [ ]cp_spliced spliced copy(in [ ]cp_spliced[[' '' ']data [[' '' ']in [ ]cp_spliced out[ ] nan nan nan return indexes and cumulativ...