idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
25,600
def make_quantile_df ( data , draw_quantiles ) : dens = data [ 'density' ] . cumsum ( ) / data [ 'density' ] . sum ( ) ecdf = interp1d ( dens , data [ 'y' ] , assume_sorted = True ) ys = ecdf ( draw_quantiles ) violin_xminvs = interp1d ( data [ 'y' ] , data [ 'xminv' ] ) ( ys ) violin_xmaxvs = interp1d ( data [ 'y' ] ,...
Return a dataframe with info needed to draw quantile segments
25,601
def from_geom ( geom ) : name = geom . params [ 'stat' ] kwargs = geom . _kwargs if ( not isinstance ( name , type ) and hasattr ( name , 'compute_layer' ) ) : return name if isinstance ( name , stat ) : return name elif isinstance ( name , type ) and issubclass ( name , stat ) : klass = name elif is_string ( name ) : ...
Return an instantiated stat object
25,602
def aesthetics ( cls ) : aesthetics = cls . REQUIRED_AES . copy ( ) calculated = get_calculated_aes ( cls . DEFAULT_AES ) for ae in set ( cls . DEFAULT_AES ) - set ( calculated ) : aesthetics . add ( ae ) return aesthetics
Return a set of all non - computed aesthetics for this stat .
25,603
def compute_layer ( cls , data , params , layout ) : check_required_aesthetics ( cls . REQUIRED_AES , list ( data . columns ) + list ( params . keys ( ) ) , cls . __name__ ) data = remove_missing ( data , na_rm = params . get ( 'na_rm' , False ) , vars = list ( cls . REQUIRED_AES | cls . NON_MISSING_AES ) , name = cls ...
Calculate statistics for this layers
25,604
def compute_panel ( cls , data , scales , ** params ) : if not len ( data ) : return type ( data ) ( ) stats = [ ] for _ , old in data . groupby ( 'group' ) : new = cls . compute_group ( old , scales , ** params ) unique = uniquecols ( old ) missing = unique . columns . difference ( new . columns ) u = unique . loc [ [...
Calculate the stats of all the groups and return the results in a single dataframe .
25,605
def kde_scipy ( data , grid , ** kwargs ) : kde = gaussian_kde ( data . T , ** kwargs ) return kde . evaluate ( grid . T )
Kernel Density Estimation with Scipy
25,606
def kde_statsmodels_u ( data , grid , ** kwargs ) : kde = KDEUnivariate ( data ) kde . fit ( ** kwargs ) return kde . evaluate ( grid )
Univariate Kernel Density Estimation with Statsmodels
25,607
def kde_statsmodels_m ( data , grid , ** kwargs ) : kde = KDEMultivariate ( data , ** kwargs ) return kde . pdf ( grid )
Multivariate Kernel Density Estimation with Statsmodels
25,608
def kde_sklearn ( data , grid , ** kwargs ) : kde_skl = KernelDensity ( ** kwargs ) kde_skl . fit ( data ) log_pdf = kde_skl . score_samples ( grid ) return np . exp ( log_pdf )
Kernel Density Estimation with Scikit - learn
25,609
def kde ( data , grid , package , ** kwargs ) : if package == 'statsmodels' : package = 'statsmodels-m' func = KDE_FUNCS [ package ] return func ( data , grid , ** kwargs )
Kernel Density Estimation
25,610
def strategy ( data , params ) : width = params [ 'width' ] with suppress ( TypeError ) : iter ( width ) width = np . asarray ( width ) width = width [ data . index ] udata_group = data [ 'group' ] . drop_duplicates ( ) n = params . get ( 'n' , None ) if n is None : n = len ( udata_group ) if n == 1 : return data if no...
Dodge overlapping interval
25,611
def parse_grid_facets ( facets ) : valid_seqs = [ "('var1', '.')" , "('var1', 'var2')" , "('.', 'var1')" , "((var1, var2), (var3, var4))" ] error_msg_s = ( "Valid sequences for specifying 'facets' look like" " {}" . format ( valid_seqs ) ) valid_forms = [ 'var1 ~ .' , 'var1 ~ var2' , '. ~ var1' , 'var1 + var2 ~ var3 + ...
Return two lists of facetting variables for the rows & columns
25,612
def expand_default ( self , scale , discrete = ( 0 , 0.6 , 0 , 0.6 ) , continuous = ( 0.05 , 0 , 0.05 , 0 ) ) : if is_waive ( scale . expand ) : if isinstance ( scale , scale_discrete ) : return discrete elif isinstance ( scale , scale_continuous ) : return continuous else : name = scale . __class__ . __name__ msg = "F...
Expand a single scale
25,613
def dict_to_table ( header , contents ) : def to_text ( row ) : name , value = row m = max_col1_size + 1 - len ( name ) spacing = ' ' * m return '' . join ( [ name , spacing , value ] ) thead = tuple ( str ( col ) for col in header ) rows = [ ] for name , value in contents . items ( ) : if value != '' : if isinstance (...
Convert dict to table
25,614
def make_signature ( name , params , common_params , common_param_values ) : tokens = [ ] seen = set ( ) def tokens_append ( key , value ) : if isinstance ( value , str ) : value = "'{}'" . format ( value ) tokens . append ( '{}={}' . format ( key , value ) ) for key in common_params : seen . add ( key ) try : value = ...
Create a signature for a geom or stat
25,615
def docstring_section_lines ( docstring , section_name ) : lines = [ ] inside_section = False underline = '-' * len ( section_name ) expect_underline = False for line in docstring . splitlines ( ) : _line = line . strip ( ) . lower ( ) if expect_underline : expect_underline = False if _line == underline : inside_sectio...
Return a section of a numpydoc string
25,616
def parameters_str_to_dict ( param_section ) : d = OrderedDict ( ) previous_param = None param_desc = None for line in param_section . split ( '\n' ) : param = param_spec ( line ) if param : if previous_param : d [ previous_param ] = '\n' . join ( param_desc ) param_desc = [ line ] previous_param = param elif param_des...
Convert a param section to a dict
25,617
def document_geom ( geom ) : docstring = dedent ( geom . __doc__ ) signature = make_signature ( geom . __name__ , geom . DEFAULT_PARAMS , common_geom_params , common_geom_param_values ) usage = GEOM_SIGNATURE_TPL . format ( signature = signature ) contents = OrderedDict ( ( '**{}**' . format ( ae ) , '' ) for ae in sor...
Create a structured documentation for the geom
25,618
def document_stat ( stat ) : docstring = dedent ( stat . __doc__ ) signature = make_signature ( stat . __name__ , stat . DEFAULT_PARAMS , common_stat_params , common_stat_param_values ) usage = STAT_SIGNATURE_TPL . format ( signature = signature ) contents = OrderedDict ( ( '**{}**' . format ( ae ) , '' ) for ae in sor...
Create a structured documentation for the stat
25,619
def document_scale ( cls ) : params_list = [ ] cls_param_string = docstring_parameters_section ( cls ) cls_param_dict = parameters_str_to_dict ( cls_param_string ) cls_params = set ( cls_param_dict . keys ( ) ) for i , base in enumerate ( cls . __bases__ ) : base_param_string = param_string = docstring_parameters_secti...
Create a documentation for a scale
25,620
def document ( cls ) : if cls . __doc__ is None : return cls baseclass_name = cls . mro ( ) [ - 2 ] . __name__ try : return DOC_FUNCTIONS [ baseclass_name ] ( cls ) except KeyError : return cls
Decorator to document a class
25,621
def _draw_using_figure ( self , figure , axs ) : self = deepcopy ( self ) self . _build ( ) self . theme = self . theme or theme_get ( ) self . figure = figure self . axs = axs try : with mpl . rc_context ( ) : self . theme . apply_rcparams ( ) self . _setup_parameters ( ) self . _draw_layers ( ) self . _draw_facet_lab...
Draw onto already created figure and axes
25,622
def _build ( self ) : if not self . layers : self += geom_blank ( ) self . layout = Layout ( ) layers = self . layers scales = self . scales layout = self . layout layers . generate_data ( self . data ) layout . setup ( layers , self ) layers . compute_aesthetics ( self ) layers . transform ( scales ) layout . train_po...
Build ggplot for rendering .
25,623
def _setup_parameters ( self ) : self . facet . set ( layout = self . layout , theme = self . theme , coordinates = self . coordinates , figure = self . figure , axs = self . axs ) self . layout . axs = self . axs self . theme . figure = self . figure
Set facet properties
25,624
def _create_figure ( self ) : if get_option ( 'close_all_figures' ) : plt . close ( 'all' ) figure = plt . figure ( ) axs = self . facet . make_axes ( figure , self . layout . layout , self . coordinates ) figure . _themeable = { } self . figure = figure self . axs = axs return figure , axs
Create Matplotlib figure and axes
25,625
def _draw_facet_labels ( self ) : for pidx , layout_info in self . layout . layout . iterrows ( ) : panel_params = self . layout . panel_params [ pidx ] self . facet . set_breaks_and_labels ( panel_params , layout_info , pidx ) self . facet . draw_label ( layout_info , pidx )
Draw facet labels a . k . a strip texts
25,626
def _draw_legend ( self ) : legend_box = self . guides . build ( self ) if not legend_box : return figure = self . figure left = figure . subplotpars . left right = figure . subplotpars . right top = figure . subplotpars . top bottom = figure . subplotpars . bottom W , H = figure . get_size_inches ( ) position = self ....
Draw legend onto the figure
25,627
def _draw_labels ( self ) : figure = self . figure get_property = self . theme . themeables . property try : margin = get_property ( 'axis_title_x' , 'margin' ) except KeyError : pad_x = 5 else : pad_x = margin . get_as ( 't' , 'pt' ) try : margin = get_property ( 'axis_title_y' , 'margin' ) except KeyError : pad_y = 5...
Draw x and y labels onto the figure
25,628
def _draw_title ( self ) : figure = self . figure title = self . labels . get ( 'title' , '' ) rcParams = self . theme . rcParams get_property = self . theme . themeables . property top = figure . subplotpars . top W , H = figure . get_size_inches ( ) try : fontsize = get_property ( 'plot_title' , 'size' ) except KeyEr...
Draw title onto the figure
25,629
def _apply_theme ( self ) : self . theme . apply_axs ( self . axs ) self . theme . apply_figure ( self . figure )
Apply theme attributes to Matplotlib objects
25,630
def _save_filename ( self , ext ) : hash_token = abs ( self . __hash__ ( ) ) return 'plotnine-save-{}.{}' . format ( hash_token , ext )
Default filename used by the save method
25,631
def save ( self , filename = None , format = None , path = None , width = None , height = None , units = 'in' , dpi = None , limitsize = True , verbose = True , ** kwargs ) : fig_kwargs = { 'bbox_inches' : 'tight' , 'format' : format } fig_kwargs . update ( kwargs ) figure = [ None ] if filename is None : ext = format ...
Save a ggplot object as an image file
25,632
def mavg ( data , xseq , ** params ) : window = params [ 'method_args' ] [ 'window' ] rolling = data [ 'y' ] . rolling ( ** params [ 'method_args' ] ) y = rolling . mean ( ) [ window : ] n = len ( data ) stderr = rolling . std ( ) [ window : ] x = data [ 'x' ] [ window : ] data = pd . DataFrame ( { 'x' : x , 'y' : y } ...
Fit moving average
25,633
def gpr ( data , xseq , ** params ) : try : from sklearn import gaussian_process except ImportError : raise PlotnineError ( "To use gaussian process smoothing, " "You need to install scikit-learn." ) kwargs = params [ 'method_args' ] if not kwargs : warnings . warn ( "See sklearn.gaussian_process.GaussianProcessRegress...
Fit gaussian process
25,634
def tdist_ci ( x , df , stderr , level ) : q = ( 1 + level ) / 2 delta = stats . t . ppf ( q , df ) * stderr return x - delta , x + delta
Confidence Intervals using the t - distribution
25,635
def wls_prediction_std ( res , exog = None , weights = None , alpha = 0.05 , interval = 'confidence' ) : covb = res . cov_params ( ) if exog is None : exog = res . model . exog predicted = res . fittedvalues if weights is None : weights = res . model . weights else : exog = np . atleast_2d ( exog ) if covb . shape [ 1 ...
calculate standard deviation and confidence interval
25,636
def setup ( self , layers , plot ) : data = [ l . data for l in layers ] self . facet = plot . facet self . facet . setup_params ( data ) data = self . facet . setup_data ( data ) self . coord = plot . coordinates self . coord . setup_params ( data ) data = self . coord . setup_data ( data ) data = self . facet . setup...
Create a layout for the panels
25,637
def train_position ( self , layers , x_scale , y_scale ) : layout = self . layout if self . panel_scales_x is None and x_scale : result = self . facet . init_scales ( layout , x_scale , None ) self . panel_scales_x = result . x if self . panel_scales_y is None and y_scale : result = self . facet . init_scales ( layout ...
Create all the required x & y panel_scales y_scales and set the ranges for each scale according to the data .
25,638
def get_scales ( self , i ) : bool_idx = ( np . asarray ( self . layout [ 'PANEL' ] ) == i ) xsc = None ysc = None if self . panel_scales_x : idx = self . layout . loc [ bool_idx , 'SCALE_X' ] . values [ 0 ] xsc = self . panel_scales_x [ idx - 1 ] if self . panel_scales_y : idx = self . layout . loc [ bool_idx , 'SCALE...
Return x & y scales for panel i
25,639
def reset_position_scales ( self ) : if not self . facet . shrink : return with suppress ( AttributeError ) : self . panel_scales_x . reset ( ) with suppress ( AttributeError ) : self . panel_scales_y . reset ( )
Reset x and y scales
25,640
def setup_panel_params ( self , coord ) : if not self . panel_scales_x : raise PlotnineError ( 'Missing an x scale' ) if not self . panel_scales_y : raise PlotnineError ( 'Missing a y scale' ) self . panel_params = [ ] cols = [ 'SCALE_X' , 'SCALE_Y' ] for i , j in self . layout [ cols ] . itertuples ( index = False ) :...
Calculate the x & y range & breaks information for each panel
25,641
def finish_data ( self , layers ) : for layer in layers : layer . data = self . facet . finish_data ( layer . data , self )
Modify data before it is drawn out by the geom
25,642
def _set_defaults ( self ) : valid_locations = { 'top' , 'bottom' , 'left' , 'right' } horizontal_locations = { 'left' , 'right' } get_property = self . theme . themeables . property margin_location_lookup = { 't' : 'b' , 'b' : 't' , 'l' : 'r' , 'r' : 'l' } self . label_position = self . label_position or 'right' if se...
Set configuration parameters for drawing guide
25,643
def legend_aesthetics ( self , layer , plot ) : l = layer legend_ae = set ( self . key . columns ) - { 'label' } all_ae = ( l . mapping . keys ( ) | ( plot . mapping if l . inherit_aes else set ( ) ) | l . stat . DEFAULT_AES . keys ( ) ) geom_ae = l . geom . REQUIRED_AES | l . geom . DEFAULT_AES . keys ( ) matched = al...
Return the aesthetics that contribute to the legend
25,644
def train_df ( self , df ) : aesthetics = sorted ( set ( self . aesthetics ) & set ( df . columns ) ) for ae in aesthetics : self . train ( df [ ae ] )
Train scale from a dataframe
25,645
def train ( self , scale , aesthetic = None ) : if aesthetic is None : aesthetic = scale . aesthetics [ 0 ] breaks = scale . get_breaks ( ) if isinstance ( breaks , OrderedDict ) : if all ( [ np . isnan ( x ) for x in breaks . values ( ) ] ) : return None elif not len ( breaks ) or all ( np . isnan ( breaks ) ) : retur...
Create the key for the guide
25,646
def create_geoms ( self , plot ) : def get_legend_geom ( layer ) : if hasattr ( layer . geom , 'draw_legend' ) : geom = layer . geom . __class__ else : name = 'geom_{}' . format ( layer . geom . legend_geom ) geom = Registry [ name ] return geom self . glayers = [ ] for l in plot . layers : exclude = set ( ) if isinsta...
Make information needed to draw a legend for each of the layers .
25,647
def get_package_data ( ) : baseline_images = [ 'tests/baseline_images/%s/*' % x for x in os . listdir ( 'plotnine/tests/baseline_images' ) ] csv_data = [ 'data/*.csv' ] package_data = { 'plotnine' : baseline_images + csv_data } return package_data
Return package data
25,648
def _get_all_imports ( ) : import types lst = [ name for name , obj in globals ( ) . items ( ) if not ( name . startswith ( '_' ) or name == 'absolute_import' or isinstance ( obj , types . ModuleType ) ) ] return lst
Return list of all the imports
25,649
def _rectangles_to_polygons ( df ) : n = len ( df ) xmin_idx = np . tile ( [ True , True , False , False ] , n ) xmax_idx = ~ xmin_idx ymin_idx = np . tile ( [ True , False , False , True ] , n ) ymax_idx = ~ ymin_idx x = np . empty ( n * 4 ) y = np . empty ( n * 4 ) x [ xmin_idx ] = df [ 'xmin' ] . repeat ( 2 ) x [ xm...
Convert rect data to polygons
25,650
def rename_aesthetics ( obj ) : if isinstance ( obj , dict ) : for name in obj : new_name = name . replace ( 'colour' , 'color' ) if name != new_name : obj [ new_name ] = obj . pop ( name ) else : obj = [ name . replace ( 'colour' , 'color' ) for name in obj ] return obj
Rename aesthetics in obj
25,651
def get_calculated_aes ( aesthetics ) : calculated_aesthetics = [ ] for name , value in aesthetics . items ( ) : if is_calculated_aes ( value ) : calculated_aesthetics . append ( name ) return calculated_aesthetics
Return a list of the aesthetics that are calculated
25,652
def is_calculated_aes ( ae ) : if not isinstance ( ae , str ) : return False for pattern in ( STAT_RE , DOTS_RE ) : if pattern . search ( ae ) : return True return False
Return a True if of the aesthetics that are calculated
25,653
def strip_stat ( value ) : def strip_hanging_closing_parens ( s ) : stack = 0 idx = [ ] for i , c in enumerate ( s ) : if c == '(' : stack += 1 elif c == ')' : stack -= 1 if stack < 0 : idx . append ( i ) stack = 0 continue yield c with suppress ( TypeError ) : if STAT_RE . search ( value ) : value = re . sub ( r'\bsta...
Remove calc function that mark calculated aesthetics
25,654
def is_position_aes ( vars_ ) : try : return all ( [ aes_to_scale ( v ) in { 'x' , 'y' } for v in vars_ ] ) except TypeError : return aes_to_scale ( vars_ ) in { 'x' , 'y' }
Figure out if an aesthetic is a position aesthetic or not
25,655
def make_labels ( mapping ) : labels = mapping . copy ( ) for ae in labels : labels [ ae ] = strip_calculated_markers ( labels [ ae ] ) return labels
Convert aesthetic mapping into text labels
25,656
def is_valid_aesthetic ( value , ae ) : if ae == 'linetype' : named = { 'solid' , 'dashed' , 'dashdot' , 'dotted' , '_' , '--' , '-.' , ':' , 'None' , ' ' , '' } if value in named : return True conditions = [ isinstance ( value , tuple ) , isinstance ( value [ 0 ] , int ) , isinstance ( value [ 1 ] , tuple ) , len ( va...
Return True if value looks valid .
25,657
def parse_wrap_facets ( facets ) : valid_forms = [ '~ var1' , '~ var1 + var2' ] error_msg = ( "Valid formula for 'facet_wrap' look like" " {}" . format ( valid_forms ) ) if isinstance ( facets , ( list , tuple ) ) : return facets if not isinstance ( facets , str ) : raise PlotnineError ( error_msg ) if '~' in facets : ...
Return list of facetting variables
25,658
def n2mfrow ( nr_plots ) : if nr_plots <= 3 : nrow , ncol = nr_plots , 1 elif nr_plots <= 6 : nrow , ncol = ( nr_plots + 1 ) // 2 , 2 elif nr_plots <= 12 : nrow , ncol = ( nr_plots + 2 ) // 3 , 3 else : nrow = int ( np . ceil ( np . sqrt ( nr_plots ) ) ) ncol = int ( np . ceil ( nr_plots / nrow ) ) return ( nrow , ncol...
Compute the rows and columns given the number of plots .
25,659
def spaceout_and_resize_panels ( self ) : ncol = self . ncol nrow = self . nrow figure = self . figure theme = self . theme get_property = theme . themeables . property left = figure . subplotpars . left right = figure . subplotpars . right top = figure . subplotpars . top bottom = figure . subplotpars . bottom top_str...
Adjust the spacing between the panels and resize them to meet the aspect ratio
25,660
def get_as ( self , key , units = 'pt' ) : dpi = 72 size = self . element . properties . get ( 'size' , 0 ) value = self [ key ] functions = { 'pt-lines' : lambda x : x / size , 'pt-in' : lambda x : x / dpi , 'lines-pt' : lambda x : x * size , 'lines-in' : lambda x : x * size / dpi , 'in-pt' : lambda x : x * dpi , 'in-...
Return key in given units
25,661
def discrete_columns ( df , ignore ) : lst = [ ] for col in df : if array_kind . discrete ( df [ col ] ) and ( col not in ignore ) : try : hash ( df [ col ] . iloc [ 0 ] ) except TypeError : continue lst . append ( col ) return lst
Return a list of the discrete columns in the dataframe df . ignore is a list|set|tuple with the names of the columns to skip .
25,662
def is_known_scalar ( value ) : def _is_datetime_or_timedelta ( value ) : return pd . Series ( value ) . dtype . kind in ( 'M' , 'm' ) return not np . iterable ( value ) and ( isinstance ( value , numbers . Number ) or _is_datetime_or_timedelta ( value ) )
Return True if value is a type we expect in a dataframe
25,663
def generate_data ( self , plot_data ) : if self . data is None : self . data = plot_data . copy ( ) elif hasattr ( self . data , '__call__' ) : self . data = self . data ( plot_data ) if not isinstance ( self . data , pd . DataFrame ) : raise PlotnineError ( "Data function must return a dataframe" ) else : self . data...
Generate data to be used by this layer
25,664
def layer_mapping ( self , mapping ) : if self . inherit_aes : aesthetics = defaults ( self . mapping , mapping ) else : aesthetics = self . mapping calculated = set ( get_calculated_aes ( aesthetics ) ) d = dict ( ( ae , v ) for ae , v in aesthetics . items ( ) if ( ae not in self . geom . aes_params ) and ( ae not in...
Return the mappings that are active in this layer
25,665
def compute_aesthetics ( self , plot ) : data = self . data aesthetics = self . layer_mapping ( plot . mapping ) with suppress ( KeyError ) : aesthetics [ 'group' ] = self . geom . aes_params [ 'group' ] env = EvalEnvironment . capture ( eval_env = plot . environment ) env = env . with_outer_namespace ( { 'factor' : pd...
Return a dataframe where the columns match the aesthetic mappings .
25,666
def compute_statistic ( self , layout ) : data = self . data if not len ( data ) : return type ( data ) ( ) params = self . stat . setup_params ( data ) data = self . stat . use_defaults ( data ) data = self . stat . setup_data ( data ) data = self . stat . compute_layer ( data , params , layout ) self . data = data
Compute & return statistics for this layer
25,667
def map_statistic ( self , plot ) : data = self . data if not len ( data ) : return type ( data ) ( ) aesthetics = deepcopy ( self . mapping ) if self . inherit_aes : aesthetics = defaults ( aesthetics , plot . mapping ) aesthetics = defaults ( aesthetics , self . stat . DEFAULT_AES ) new = { } stat_data = type ( data ...
Mapping aesthetics to computed statistics
25,668
def compute_position ( self , layout ) : params = self . position . setup_params ( self . data ) data = self . position . setup_data ( self . data , params ) data = self . position . compute_layer ( data , params , layout ) self . data = data
Compute the position of each geometric object in concert with the other objects in the panel
25,669
def train ( self , x ) : self . range = scale_continuous . train ( x , self . range )
Train continuous range
25,670
def train ( self , x , drop = False , na_rm = False ) : self . range = scale_discrete . train ( x , self . range , drop , na_rm = na_rm )
Train discrete range
25,671
def _margins ( vars , margins = True ) : if margins is False : return [ ] def fn ( _vars ) : "The margin variables for a given row or column" dim_margins = [ [ ] ] for i , u in enumerate ( _vars ) : if margins is True or u in margins : lst = [ u ] + [ v for v in _vars [ i + 1 : ] ] dim_margins . append ( lst ) return d...
Figure out margining variables .
25,672
def add_margins ( df , vars , margins = True ) : margin_vars = _margins ( vars , margins ) if not margin_vars : return df margin_dfs = [ df ] for vlst in margin_vars [ 1 : ] : dfx = df . copy ( ) for v in vlst : dfx . loc [ 0 : , v ] = '(all)' margin_dfs . append ( dfx ) merged = pd . concat ( margin_dfs , axis = 0 ) m...
Add margins to a data frame .
25,673
def _id_var ( x , drop = False ) : if len ( x ) == 0 : return [ ] categorical = pdtypes . is_categorical_dtype ( x ) if categorical : if drop : x = x . cat . remove_unused_categories ( ) lst = list ( x . cat . codes + 1 ) else : has_nan = any ( np . isnan ( i ) for i in x if isinstance ( i , float ) ) if has_nan : nan_...
Assign ids to items in x . If two items are the same they get the same id .
25,674
def join_keys ( x , y , by = None ) : if by is None : by = slice ( None , None , None ) if isinstance ( by , tuple ) : by = list ( by ) joint = x [ by ] . append ( y [ by ] , ignore_index = True ) keys = ninteraction ( joint , drop = True ) keys = np . asarray ( keys ) nx , ny = len ( x ) , len ( y ) return { 'x' : key...
Join keys .
25,675
def uniquecols ( df ) : bool_idx = df . apply ( lambda col : len ( np . unique ( col ) ) == 1 , axis = 0 ) df = df . loc [ : , bool_idx ] . iloc [ 0 : 1 , : ] . reset_index ( drop = True ) return df
Return unique columns
25,676
def defaults ( d1 , d2 ) : d1 = d1 . copy ( ) tolist = isinstance ( d2 , pd . DataFrame ) keys = ( k for k in d2 if k not in d1 ) for k in keys : if tolist : d1 [ k ] = d2 [ k ] . tolist ( ) else : d1 [ k ] = d2 [ k ] return d1
Update a copy of d1 with the contents of d2 that are not in d1 . d1 and d2 are dictionary like objects .
25,677
def jitter ( x , factor = 1 , amount = None , random_state = None ) : if len ( x ) == 0 : return x if random_state is None : random_state = np . random elif isinstance ( random_state , int ) : random_state = np . random . RandomState ( random_state ) x = np . asarray ( x ) try : z = np . ptp ( x [ np . isfinite ( x ) ]...
Add a small amount of noise to values in an array_like
25,678
def remove_missing ( df , na_rm = False , vars = None , name = '' , finite = False ) : n = len ( df ) if vars is None : vars = df . columns else : vars = df . columns . intersection ( vars ) if finite : lst = [ np . inf , - np . inf ] to_replace = { v : lst for v in vars } df . replace ( to_replace , np . nan , inplace...
Convenience function to remove missing values from a dataframe
25,679
def to_rgba ( colors , alpha ) : def is_iterable ( var ) : return cbook . iterable ( var ) and not is_string ( var ) def has_alpha ( c ) : if isinstance ( c , tuple ) : if len ( c ) == 4 : return True elif isinstance ( c , str ) : if c [ 0 ] == '#' and len ( c ) == 9 : return True return False def no_color ( c ) : retu...
Covert hex colors to rgba values .
25,680
def groupby_apply ( df , cols , func , * args , ** kwargs ) : try : axis = kwargs . pop ( 'axis' ) except KeyError : axis = 0 lst = [ ] for _ , d in df . groupby ( cols ) : lst . append ( func ( d , * args , ** kwargs ) ) return pd . concat ( lst , axis = axis , ignore_index = True )
Groupby cols and call the function fn on each grouped dataframe .
25,681
def pivot_apply ( df , column , index , func , * args , ** kwargs ) : def _func ( x ) : return func ( x , * args , ** kwargs ) return df . pivot_table ( column , index , aggfunc = _func ) [ column ]
Apply a function to each group of a column
25,682
def copy_keys ( source , destination , keys = None ) : if keys is None : keys = destination . keys ( ) for k in set ( source ) & set ( keys ) : destination [ k ] = source [ k ] return destination
Add keys in source to destination
25,683
def alias ( name , class_object ) : module = inspect . getmodule ( class_object ) module . __dict__ [ name ] = class_object if isinstance ( class_object , Registry ) : Registry [ name ] = class_object
Create an alias of a class object
25,684
def get_kwarg_names ( func ) : sig = inspect . signature ( func ) kwonlyargs = [ p . name for p in sig . parameters . values ( ) if p . default is not p . empty ] return kwonlyargs
Return a list of valid kwargs to function func
25,685
def get_valid_kwargs ( func , potential_kwargs ) : kwargs = { } for name in get_kwarg_names ( func ) : with suppress ( KeyError ) : kwargs [ name ] = potential_kwargs [ name ] return kwargs
Return valid kwargs to function func
25,686
def copy_missing_columns ( df , ref_df ) : cols = ref_df . columns . difference ( df . columns ) _loc = ref_df . columns . get_loc l1 , l2 = len ( df ) , len ( ref_df ) if l1 >= l2 and l1 % l2 == 0 : idx = np . tile ( range ( l2 ) , l1 // l2 ) else : idx = np . repeat ( 0 , l1 ) for col in cols : df [ col ] = ref_df . ...
Copy missing columns from ref_df to df
25,687
def data_mapping_as_kwargs ( args , kwargs ) : aes = dict mapping , data = aes ( ) , None aes_err = ( "Found more than one aes argument. " "Expecting zero or one" ) data_err = "More than one dataframe argument." for arg in args : if isinstance ( arg , aes ) and mapping : raise PlotnineError ( aes_err ) if isinstance ( ...
Return kwargs with the mapping and data values
25,688
def resolution ( x , zero = True ) : x = np . asarray ( x ) _x = x [ ~ np . isnan ( x ) ] _x = ( x . min ( ) , x . max ( ) ) if x . dtype . kind in ( 'i' , 'u' ) or zero_range ( _x ) : return 1 x = np . unique ( x ) if zero : x = np . unique ( np . hstack ( [ 0 , x ] ) ) return np . min ( np . diff ( np . sort ( x ) ) ...
Compute the resolution of a data vector
25,689
def cross_join ( df1 , df2 ) : if len ( df1 ) == 0 : return df2 if len ( df2 ) == 0 : return df1 all_columns = pd . Index ( list ( df1 . columns ) + list ( df2 . columns ) ) df1 [ 'key' ] = 1 df2 [ 'key' ] = 1 return pd . merge ( df1 , df2 , on = 'key' ) . loc [ : , all_columns ]
Return a dataframe that is a cross between dataframes df1 and df2
25,690
def to_inches ( value , units ) : lookup = { 'in' : lambda x : x , 'cm' : lambda x : x / 2.54 , 'mm' : lambda x : x / ( 2.54 * 10 ) } try : return lookup [ units ] ( value ) except KeyError : raise PlotnineError ( "Unknown units '{}'" . format ( units ) )
Convert value to inches
25,691
def from_inches ( value , units ) : lookup = { 'in' : lambda x : x , 'cm' : lambda x : x * 2.54 , 'mm' : lambda x : x * 2.54 * 10 } try : return lookup [ units ] ( value ) except KeyError : raise PlotnineError ( "Unknown units '{}'" . format ( units ) )
Convert value in inches to given units
25,692
def log ( x , base = None ) : if base == 10 : return np . log10 ( x ) elif base == 2 : return np . log2 ( x ) elif base is None or base == np . e : return np . log ( x ) else : return np . log ( x ) / np . log ( base )
Calculate the log
25,693
def handle ( cls , value , context , ** kwargs ) : try : hook_name , key = value . split ( "::" ) except ValueError : raise ValueError ( "Invalid value for hook_data: %s. Must be in " "<hook_name>::<key> format." % value ) return context . hook_data [ hook_name ] [ key ]
Returns the value of a key for a given hook in hook_data .
25,694
def resolve_variables ( variables , context , provider ) : for variable in variables : variable . resolve ( context , provider )
Given a list of variables resolve all of them .
25,695
def value ( self ) : try : return self . _value . value ( ) except UnresolvedVariableValue : raise UnresolvedVariable ( "<unknown>" , self ) except InvalidLookupConcatenation as e : raise InvalidLookupCombination ( e . lookup , e . lookups , self )
Return the current value of the Variable .
25,696
def resolve ( self , context , provider ) : try : self . _value . resolve ( context , provider ) except FailedLookup as e : raise FailedVariableLookup ( self . name , e . lookup , e . error )
Recursively resolve any lookups with the Variable .
25,697
def run ( self ) : stop_watcher = threading . Event ( ) watcher = None if self . watch_func : watcher = threading . Thread ( target = self . watch_func , args = ( self . stack , stop_watcher ) ) watcher . start ( ) try : while not self . done : self . _run_once ( ) finally : if watcher : stop_watcher . set ( ) watcher ...
Runs this step until it has completed successfully or been skipped .
25,698
def downstream ( self , step_name ) : return list ( self . steps [ dep ] for dep in self . dag . downstream ( step_name ) )
Returns the direct dependencies of the given step
25,699
def transposed ( self ) : return Graph ( steps = self . steps , dag = self . dag . transpose ( ) )
Returns a transposed version of this graph . Useful for walking in reverse .