idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
15,400
def best ( self ) : return pd . Series ( { "name" : self . best_dist . name , "params" : self . best_param , "sse" : self . best_sse , } )
The resulting best - fit distribution its parameters and SSE .
15,401
def all ( self , by = "name" , ascending = True ) : res = pd . DataFrame ( { "name" : self . distributions , "params" : self . params , "sse" : self . sses , } ) [ [ "name" , "sse" , "params" ] ] res . sort_values ( by = by , ascending = ascending , inplace = True ) return res
All tested distributions their parameters and SSEs .
15,402
def plot ( self ) : plt . plot ( self . bin_edges , self . hist , self . bin_edges , self . best_pdf )
Plot the empirical histogram versus best - fit distribution s PDF .
15,403
def eigen_table ( self ) : idx = [ "Eigenvalue" , "Variability (%)" , "Cumulative (%)" ] table = pd . DataFrame ( np . array ( [ self . eigenvalues , self . inertia , self . cumulative_inertia ] ) , columns = [ "F%s" % i for i in range ( 1 , self . keep + 1 ) ] , index = idx , ) return table
Eigenvalues expl . variance and cumulative expl . variance .
15,404
def optimize ( self ) : def te ( weights , r , proxies ) : if isinstance ( weights , list ) : weights = np . array ( weights ) proxy = np . sum ( proxies * weights , axis = 1 ) te = np . std ( proxy - r ) return te ew = utils . equal_weights ( n = self . n , sumto = self . sumto ) bnds = tuple ( ( 0 , 1 ) for x in range ( self . n ) ) cons = { "type" : "eq" , "fun" : lambda x : np . sum ( x ) - self . sumto } xs = [ ] funs = [ ] for i , j in zip ( self . _r , self . _proxies ) : opt = sco . minimize ( te , x0 = ew , args = ( i , j ) , method = "SLSQP" , bounds = bnds , constraints = cons , ) x , fun = opt [ "x" ] , opt [ "fun" ] xs . append ( x ) funs . append ( fun ) self . _xs = np . array ( xs ) self . _funs = np . array ( funs ) return self
Analogous to sklearn s fit . Returns self to enable chaining .
15,405
def replicate ( self ) : return np . sum ( self . proxies [ self . window : ] * self . _xs [ : - 1 ] , axis = 1 ) . reindex ( self . r . index )
Forward - month returns of the replicating portfolio .
15,406
def _try_to_squeeze ( obj , raise_ = False ) : if isinstance ( obj , pd . Series ) : return obj elif isinstance ( obj , pd . DataFrame ) and obj . shape [ - 1 ] == 1 : return obj . squeeze ( ) else : if raise_ : raise ValueError ( "Input cannot be squeezed." ) return obj
Attempt to squeeze to 1d Series .
15,407
def anlzd_stdev ( self , ddof = 0 , freq = None , ** kwargs ) : if freq is None : freq = self . _try_get_freq ( ) if freq is None : raise FrequencyError ( msg ) return nanstd ( self , ddof = ddof ) * freq ** 0.5
Annualized standard deviation with ddof degrees of freedom .
15,408
def batting_avg ( self , benchmark ) : diff = self . excess_ret ( benchmark ) return np . count_nonzero ( diff > 0.0 ) / diff . count ( )
Percentage of periods when self outperformed benchmark .
15,409
def beta_adj ( self , benchmark , adj_factor = 2 / 3 , ** kwargs ) : beta = self . beta ( benchmark = benchmark , ** kwargs ) return adj_factor * beta + ( 1 - adj_factor )
Adjusted beta .
15,410
def down_capture ( self , benchmark , threshold = 0.0 , compare_op = "lt" ) : slf , bm = self . downmarket_filter ( benchmark = benchmark , threshold = threshold , compare_op = compare_op , include_benchmark = True , ) return slf . geomean ( ) / bm . geomean ( )
Downside capture ratio .
15,411
def downmarket_filter ( self , benchmark , threshold = 0.0 , compare_op = "lt" , include_benchmark = False , ) : return self . _mkt_filter ( benchmark = benchmark , threshold = threshold , compare_op = compare_op , include_benchmark = include_benchmark , )
Drop elementwise samples where benchmark > threshold .
15,412
def drawdown_end ( self , return_date = False ) : end = self . drawdown_idx ( ) . idxmin ( ) if return_date : return end . date ( ) return end
The date of the drawdown trough .
15,413
def drawdown_idx ( self ) : ri = self . ret_idx ( ) return ri / np . maximum ( ri . cummax ( ) , 1.0 ) - 1.0
Drawdown index ; TSeries of drawdown from running HWM .
15,414
def drawdown_length ( self , return_int = False ) : td = self . drawdown_end ( ) - self . drawdown_start ( ) if return_int : return td . days return td
Length of drawdown in days .
15,415
def drawdown_recov ( self , return_int = False ) : td = self . recov_date ( ) - self . drawdown_end ( ) if return_int : return td . days return td
Length of drawdown recovery in days .
15,416
def drawdown_start ( self , return_date = False ) : dd = self . drawdown_idx ( ) mask = nancumsum ( dd == nanmin ( dd . min ) ) . astype ( bool ) start = dd . mask ( mask ) [ : : - 1 ] . idxmax ( ) if return_date : return start . date ( ) return start
The date of the peak at which most severe drawdown began .
15,417
def excess_drawdown_idx ( self , benchmark , method = "caer" ) : if isinstance ( method , ( int , float ) ) : method = [ "caer" , "cger" , "ecr" , "ecrr" ] [ method ] method = method . lower ( ) if method == "caer" : er = self . excess_ret ( benchmark = benchmark , method = "arithmetic" ) return er . drawdown_idx ( ) elif method == "cger" : er = self . excess_ret ( benchmark = benchmark , method = "geometric" ) return er . drawdown_idx ( ) elif method == "ecr" : er = self . ret_idx ( ) - benchmark . ret_idx ( ) + 1 if er . isnull ( ) . any ( ) : return er / er . cummax ( ) - 1.0 else : return er / np . maximum . accumulate ( er ) - 1.0 elif method == "ecrr" : p = self . ret_idx ( ) . values b = benchmark . ret_idx ( ) . values er = p - b if er . isnull ( ) . any ( ) : cam = self . expanding ( min_periods = 1 ) . apply ( lambda x : x . argmax ( ) ) else : cam = utils . cumargmax ( er ) p0 = p [ cam ] b0 = b [ cam ] return ( p * b0 - b * p0 ) / ( p0 * b0 ) else : raise ValueError ( "`method` must be one of" " ('caer', 'cger', 'ecr', 'ecrr')," " case-insensitive, or" " an integer mapping to these methods" " (1 thru 4)." )
Excess drawdown index ; TSeries of excess drawdowns .
15,418
def excess_ret ( self , benchmark , method = "arithmetic" ) : if method . startswith ( "arith" ) : return self - _try_to_squeeze ( benchmark ) elif method . startswith ( "geo" ) : return ( self . ret_rels ( ) / _try_to_squeeze ( benchmark ) . ret_rels ( ) - 1.0 )
Excess return .
15,419
def gain_to_loss_ratio ( self ) : gt = self > 0 lt = self < 0 return ( nansum ( gt ) / nansum ( lt ) ) * ( self [ gt ] . mean ( ) / self [ lt ] . mean ( ) )
Gain - to - loss ratio ratio of positive to negative returns .
15,420
def msquared ( self , benchmark , rf = 0.02 , ddof = 0 ) : rf = self . _validate_rf ( rf ) scaling = benchmark . anlzd_stdev ( ddof ) / self . anlzd_stdev ( ddof ) diff = self . anlzd_ret ( ) - rf return rf + diff * scaling
M - squared return scaled by relative total risk .
15,421
def pct_negative ( self , threshold = 0.0 ) : return np . count_nonzero ( self [ self < threshold ] ) / self . count ( )
Pct . of periods in which self is less than threshold .
15,422
def pct_positive ( self , threshold = 0.0 ) : return np . count_nonzero ( self [ self > threshold ] ) / self . count ( )
Pct . of periods in which self is greater than threshold .
15,423
def recov_date ( self , return_date = False ) : dd = self . drawdown_idx ( ) mask = nancumprod ( dd != nanmin ( dd ) ) . astype ( bool ) res = dd . mask ( mask ) == 0 if not res . any ( ) : recov = pd . NaT else : recov = res . idxmax ( ) if return_date : return recov . date ( ) return recov
Drawdown recovery date .
15,424
def rollup ( self , freq , ** kwargs ) : return self . ret_rels ( ) . resample ( freq , ** kwargs ) . prod ( ) - 1.0
Downsample self through geometric linking .
15,425
def semi_stdev ( self , threshold = 0.0 , ddof = 0 , freq = None ) : if freq is None : freq = self . _try_get_freq ( ) if freq is None : raise FrequencyError ( msg ) n = self . count ( ) - ddof ss = ( nansum ( np . minimum ( self - threshold , 0.0 ) ** 2 ) ** 0.5 ) / n return ss * freq ** 0.5
Semi - standard deviation ; stdev of downside returns .
15,426
def sharpe_ratio ( self , rf = 0.02 , ddof = 0 ) : rf = self . _validate_rf ( rf ) stdev = self . anlzd_stdev ( ddof = ddof ) return ( self . anlzd_ret ( ) - rf ) / stdev
Return over rf per unit of total risk .
15,427
def sortino_ratio ( self , threshold = 0.0 , ddof = 0 , freq = None ) : stdev = self . semi_stdev ( threshold = threshold , ddof = ddof , freq = freq ) return ( self . anlzd_ret ( ) - threshold ) / stdev
Return over a threshold per unit of downside deviation .
15,428
def tracking_error ( self , benchmark , ddof = 0 ) : er = self . excess_ret ( benchmark = benchmark ) return er . anlzd_stdev ( ddof = ddof )
Standard deviation of excess returns .
15,429
def treynor_ratio ( self , benchmark , rf = 0.02 ) : benchmark = _try_to_squeeze ( benchmark ) if benchmark . ndim > 1 : raise ValueError ( "Treynor ratio requires a single benchmark" ) rf = self . _validate_rf ( rf ) beta = self . beta ( benchmark ) return ( self . anlzd_ret ( ) - rf ) / beta
Return over rf per unit of systematic risk .
15,430
def up_capture ( self , benchmark , threshold = 0.0 , compare_op = "ge" ) : slf , bm = self . upmarket_filter ( benchmark = benchmark , threshold = threshold , compare_op = compare_op , include_benchmark = True , ) return slf . geomean ( ) / bm . geomean ( )
Upside capture ratio .
15,431
def upmarket_filter ( self , benchmark , threshold = 0.0 , compare_op = "ge" , include_benchmark = False , ) : return self . _mkt_filter ( benchmark = benchmark , threshold = threshold , compare_op = compare_op , include_benchmark = include_benchmark , )
Drop elementwise samples where benchmark < threshold .
15,432
def CAPM ( self , benchmark , has_const = False , use_const = True ) : return ols . OLS ( y = self , x = benchmark , has_const = has_const , use_const = use_const )
Interface to OLS regression against benchmark .
15,433
def load_retaildata ( ) : db = { "Auto, other Motor Vehicle" : "https://www.census.gov/retail/marts/www/adv441x0.txt" , "Building Material and Garden Equipment and Supplies Dealers" : "https://www.census.gov/retail/marts/www/adv44400.txt" , "Clothing and Clothing Accessories Stores" : "https://www.census.gov/retail/marts/www/adv44800.txt" , "Dept. Stores (ex. leased depts)" : "https://www.census.gov/retail/marts/www/adv45210.txt" , "Electronics and Appliance Stores" : "https://www.census.gov/retail/marts/www/adv44300.txt" , "Food Services and Drinking Places" : "https://www.census.gov/retail/marts/www/adv72200.txt" , "Food and Beverage Stores" : "https://www.census.gov/retail/marts/www/adv44500.txt" , "Furniture and Home Furnishings Stores" : "https://www.census.gov/retail/marts/www/adv44200.txt" , "Gasoline Stations" : "https://www.census.gov/retail/marts/www/adv44700.txt" , "General Merchandise Stores" : "https://www.census.gov/retail/marts/www/adv45200.txt" , "Grocery Stores" : "https://www.census.gov/retail/marts/www/adv44510.txt" , "Health and Personal Care Stores" : "https://www.census.gov/retail/marts/www/adv44600.txt" , "Miscellaneous Store Retailers" : "https://www.census.gov/retail/marts/www/adv45300.txt" , "Motor Vehicle and Parts Dealers" : "https://www.census.gov/retail/marts/www/adv44100.txt" , "Nonstore Retailers" : "https://www.census.gov/retail/marts/www/adv45400.txt" , "Retail and Food Services, total" : "https://www.census.gov/retail/marts/www/adv44x72.txt" , "Retail, total" : "https://www.census.gov/retail/marts/www/adv44000.txt" , "Sporting Goods, Hobby, Book, and Music Stores" : "https://www.census.gov/retail/marts/www/adv45100.txt" , "Total (excl. Motor Vehicle)" : "https://www.census.gov/retail/marts/www/adv44y72.txt" , "Retail (excl. Motor Vehicle and Parts Dealers)" : "https://www.census.gov/retail/marts/www/adv4400a.txt" , } dct = { } for key , value in db . items ( ) : data = pd . read_csv ( value , skiprows = 5 , skip_blank_lines = True , header = None , sep = "\s+" , index_col = 0 , ) try : cut = data . index . get_loc ( "SEASONAL" ) except KeyError : cut = data . index . get_loc ( "NO" ) data = data . iloc [ : cut ] data = data . apply ( lambda col : pd . to_numeric ( col , downcast = "float" ) ) data = data . stack ( ) year = data . index . get_level_values ( 0 ) month = data . index . get_level_values ( 1 ) idx = pd . to_datetime ( { "year" : year , "month" : month , "day" : 1 } ) + offsets . MonthEnd ( 1 ) data . index = idx data . name = key dct [ key ] = data sales = pd . DataFrame ( dct ) sales = sales . reindex ( pd . date_range ( sales . index [ 0 ] , sales . index [ - 1 ] , freq = "M" ) ) yoy = sales . pct_change ( periods = 12 ) return sales , yoy
Monthly retail trade data from census . gov .
15,434
def avail ( df ) : avail = DataFrame ( { "start" : df . apply ( lambda col : col . first_valid_index ( ) ) , "end" : df . apply ( lambda col : col . last_valid_index ( ) ) , } ) return avail [ [ "start" , "end" ] ]
Return start & end availability for each column in a DataFrame .
15,435
def _uniquewords ( * args ) : words = { } n = 0 for word in itertools . chain ( * args ) : if word not in words : words [ word ] = n n += 1 return words
Dictionary of words to their indices . Helper function to encode .
15,436
def encode ( * args ) : args = [ arg . split ( ) for arg in args ] unique = _uniquewords ( * args ) feature_vectors = np . zeros ( ( len ( args ) , len ( unique ) ) ) for vec , s in zip ( feature_vectors , args ) : for word in s : vec [ unique [ word ] ] = 1 return feature_vectors
One - hot encode the given input strings .
15,437
def unique_everseen ( iterable , filterfalse_ = itertools . filterfalse ) : seen = set ( ) seen_add = seen . add for element in filterfalse_ ( seen . __contains__ , iterable ) : seen_add ( element ) yield element
Unique elements preserving order .
15,438
def dispatch ( self , * args , ** kwargs ) : return super ( GetAppListJsonView , self ) . dispatch ( * args , ** kwargs )
Only staff members can access this view
15,439
def get ( self , request ) : self . app_list = site . get_app_list ( request ) self . apps_dict = self . create_app_list_dict ( ) items = get_config ( 'MENU' ) if not items : voices = self . get_default_voices ( ) else : voices = [ ] for item in items : self . add_voice ( voices , item ) return JsonResponse ( voices , safe = False )
Returns a json representing the menu voices in a format eaten by the js menu . Raised ImproperlyConfigured exceptions can be viewed in the browser console
15,440
def add_voice ( self , voices , item ) : voice = None if item . get ( 'type' ) == 'title' : voice = self . get_title_voice ( item ) elif item . get ( 'type' ) == 'app' : voice = self . get_app_voice ( item ) elif item . get ( 'type' ) == 'model' : voice = self . get_app_model_voice ( item ) elif item . get ( 'type' ) == 'free' : voice = self . get_free_voice ( item ) if voice : voices . append ( voice )
Adds a voice to the list
15,441
def get_title_voice ( self , item ) : view = True if item . get ( 'perms' , None ) : view = self . check_user_permission ( item . get ( 'perms' , [ ] ) ) elif item . get ( 'apps' , None ) : view = self . check_apps_permission ( item . get ( 'apps' , [ ] ) ) if view : return { 'type' : 'title' , 'label' : item . get ( 'label' , '' ) , 'icon' : item . get ( 'icon' , None ) } return None
Title voice Returns the js menu compatible voice dict if the user can see it None otherwise
15,442
def get_free_voice ( self , item ) : view = True if item . get ( 'perms' , None ) : view = self . check_user_permission ( item . get ( 'perms' , [ ] ) ) elif item . get ( 'apps' , None ) : view = self . check_apps_permission ( item . get ( 'apps' , [ ] ) ) if view : return { 'type' : 'free' , 'label' : item . get ( 'label' , '' ) , 'icon' : item . get ( 'icon' , None ) , 'url' : item . get ( 'url' , None ) } return None
Free voice Returns the js menu compatible voice dict if the user can see it None otherwise
15,443
def get_app_voice ( self , item ) : if item . get ( 'name' , None ) is None : raise ImproperlyConfigured ( 'App menu voices must have a name key' ) if self . check_apps_permission ( [ item . get ( 'name' , None ) ] ) : children = [ ] if item . get ( 'models' , None ) is None : for name , model in self . apps_dict [ item . get ( 'name' ) ] [ 'models' ] . items ( ) : children . append ( { 'type' : 'model' , 'label' : model . get ( 'name' , '' ) , 'url' : model . get ( 'admin_url' , '' ) } ) else : for model_item in item . get ( 'models' , [ ] ) : voice = self . get_model_voice ( item . get ( 'name' ) , model_item ) if voice : children . append ( voice ) return { 'type' : 'app' , 'label' : item . get ( 'label' , '' ) , 'icon' : item . get ( 'icon' , None ) , 'children' : children } return None
App voice Returns the js menu compatible voice dict if the user can see it None otherwise
15,444
def get_app_model_voice ( self , app_model_item ) : if app_model_item . get ( 'name' , None ) is None : raise ImproperlyConfigured ( 'Model menu voices must have a name key' ) if app_model_item . get ( 'app' , None ) is None : raise ImproperlyConfigured ( 'Model menu voices must have an app key' ) return self . get_model_voice ( app_model_item . get ( 'app' ) , app_model_item )
App Model voice Returns the js menu compatible voice dict if the user can see it None otherwise
15,445
def get_model_voice ( self , app , model_item ) : if model_item . get ( 'name' , None ) is None : raise ImproperlyConfigured ( 'Model menu voices must have a name key' ) if self . check_model_permission ( app , model_item . get ( 'name' , None ) ) : return { 'type' : 'model' , 'label' : model_item . get ( 'label' , '' ) , 'icon' : model_item . get ( 'icon' , None ) , 'url' : self . apps_dict [ app ] [ 'models' ] [ model_item . get ( 'name' ) ] [ 'admin_url' ] , } return None
Model voice Returns the js menu compatible voice dict if the user can see it None otherwise
15,446
def create_app_list_dict ( self ) : d = { } for app in self . app_list : models = { } for model in app . get ( 'models' , [ ] ) : models [ model . get ( 'object_name' ) . lower ( ) ] = model d [ app . get ( 'app_label' ) . lower ( ) ] = { 'app_url' : app . get ( 'app_url' , '' ) , 'app_label' : app . get ( 'app_label' ) , 'models' : models } return d
Creates a more efficient to check dictionary from the app_list list obtained from django admin
15,447
def check_apps_permission ( self , apps ) : for app in apps : if app in self . apps_dict : return True return False
Checks if one of apps is listed in apps_dict Since apps_dict is derived from the app_list given by django admin it lists only the apps the user can view
15,448
def check_model_permission ( self , app , model ) : if self . apps_dict . get ( app , False ) and model in self . apps_dict [ app ] [ 'models' ] : return True return False
Checks if model is listed in apps_dict Since apps_dict is derived from the app_list given by django admin it lists only the apps and models the user can view
15,449
def get_default_voices ( self ) : voices = [ ] for app in self . app_list : children = [ ] for model in app . get ( 'models' , [ ] ) : child = { 'type' : 'model' , 'label' : model . get ( 'name' , '' ) , 'url' : model . get ( 'admin_url' , '' ) } children . append ( child ) voice = { 'type' : 'app' , 'label' : app . get ( 'name' , '' ) , 'url' : app . get ( 'app_url' , '' ) , 'children' : children } voices . append ( voice ) return voices
When no custom menu is defined in settings Retrieves a js menu ready dict from the django admin app list
15,450
def uncheckButton ( self ) : for button in self . buttons : button . blockSignals ( True ) if button . isChecked ( ) : button . setChecked ( False ) button . blockSignals ( False )
Removes the checked stated of all buttons in this widget .
15,451
def addColumn ( self , columnName , dtype , defaultValue ) : model = self . tableView . model ( ) if model is not None : model . addDataFrameColumn ( columnName , dtype , defaultValue ) self . addColumnButton . setChecked ( False )
Adds a column with the given parameters to the underlying model
15,452
def showAddColumnDialog ( self , triggered ) : if triggered : dialog = AddAttributesDialog ( self ) dialog . accepted . connect ( self . addColumn ) dialog . rejected . connect ( self . uncheckButton ) dialog . show ( )
Display the dialog to add a column to the model .
15,453
def addRow ( self , triggered ) : if triggered : model = self . tableView . model ( ) model . addDataFrameRows ( ) self . sender ( ) . setChecked ( False )
Adds a row to the model .
15,454
def removeRow ( self , triggered ) : if triggered : model = self . tableView . model ( ) selection = self . tableView . selectedIndexes ( ) rows = [ index . row ( ) for index in selection ] model . removeDataFrameRows ( set ( rows ) ) self . sender ( ) . setChecked ( False )
Removes a row to the model .
15,455
def removeColumns ( self , columnNames ) : model = self . tableView . model ( ) if model is not None : model . removeDataFrameColumns ( columnNames ) self . removeColumnButton . setChecked ( False )
Removes one or multiple columns from the model .
15,456
def setViewModel ( self , model ) : if isinstance ( model , DataFrameModel ) : self . enableEditing ( False ) self . uncheckButton ( ) selectionModel = self . tableView . selectionModel ( ) self . tableView . setModel ( model ) model . dtypeChanged . connect ( self . updateDelegate ) model . dataChanged . connect ( self . updateDelegates ) del selectionModel
Sets the model for the enclosed TableView in this widget .
15,457
def updateDelegates ( self ) : for index , column in enumerate ( self . tableView . model ( ) . dataFrame ( ) . columns ) : dtype = self . tableView . model ( ) . dataFrame ( ) [ column ] . dtype self . updateDelegate ( index , dtype )
reset all delegates
15,458
def createThread ( parent , worker , deleteWorkerLater = False ) : thread = QtCore . QThread ( parent ) thread . started . connect ( worker . doWork ) worker . finished . connect ( thread . quit ) if deleteWorkerLater : thread . finished . connect ( worker . deleteLater ) worker . moveToThread ( thread ) worker . setParent ( parent ) return thread
Create a new thread for given worker .
15,459
def description ( self , value ) : try : value = np . dtype ( value ) except TypeError as e : return None for ( dtype , string ) in self . _all : if dtype == value : return string return None
Fetches the translated description for the given datatype .
15,460
def convertTimestamps ( column ) : tempColumn = column try : tempValue = np . datetime64 ( column [ randint ( 0 , len ( column . index ) - 1 ) ] ) tempColumn = column . apply ( to_datetime ) except Exception : pass return tempColumn
Convert a dtype of a given column to a datetime .
15,461
def superReadCSV ( filepath , first_codec = 'UTF_8' , usecols = None , low_memory = False , dtype = None , parse_dates = True , sep = ',' , chunksize = None , verbose = False , ** kwargs ) : if isinstance ( filepath , pd . DataFrame ) : return filepath assert isinstance ( first_codec , str ) , "first_codec must be a string" codecs = [ 'UTF_8' , 'ISO-8859-1' , 'ASCII' , 'UTF_16' , 'UTF_32' ] try : codecs . remove ( first_codec ) except ValueError as not_in_list : pass codecs . insert ( 0 , first_codec ) errors = [ ] for c in codecs : try : return pd . read_csv ( filepath , usecols = usecols , low_memory = low_memory , encoding = c , dtype = dtype , parse_dates = parse_dates , sep = sep , chunksize = chunksize , ** kwargs ) except ( UnicodeError , UnboundLocalError ) as e : errors . append ( e ) except Exception as e : errors . append ( e ) if 'tokenizing' in str ( e ) : pass else : raise if verbose : [ print ( e ) for e in errors ] raise UnicodeDecodeError ( "Tried {} codecs and failed on all: \n CODECS: {} \n FILENAME: {}" . format ( len ( codecs ) , codecs , os . path . basename ( filepath ) ) )
A wrap to pandas read_csv with mods to accept a dataframe or filepath . returns dataframe untouched reads filepath and returns dataframe based on arguments .
15,462
def dedupe_cols ( frame ) : cols = list ( frame . columns ) for i , item in enumerate ( frame . columns ) : if item in frame . columns [ : i ] : cols [ i ] = "toDROP" frame . columns = cols return frame . drop ( "toDROP" , 1 , errors = 'ignore' )
Need to dedupe columns that have the same name .
15,463
def setEditorData ( self , spinBox , index ) : if index . isValid ( ) : value = index . model ( ) . data ( index , QtCore . Qt . EditRole ) spinBox . setValue ( value )
Sets the data to be displayed and edited by the editor from the data model item specified by the model index .
15,464
def createEditor ( self , parent , option , index ) : combo = QtGui . QComboBox ( parent ) combo . addItems ( SupportedDtypes . names ( ) ) combo . currentIndexChanged . connect ( self . currentIndexChanged ) return combo
Creates an Editor Widget for the given index .
15,465
def setEditorData ( self , editor , index ) : editor . blockSignals ( True ) data = index . data ( ) dataIndex = editor . findData ( data ) editor . setCurrentIndex ( dataIndex ) editor . blockSignals ( False )
Sets the current data for the editor .
15,466
def setModelData ( self , editor , model , index ) : model . setData ( index , editor . itemText ( editor . currentIndex ( ) ) )
Updates the model after changing data in the editor .
15,467
def accepted ( self ) : try : self . _saveModel ( ) except Exception as err : self . _statusBar . showMessage ( str ( err ) ) raise else : self . _resetWidgets ( ) self . exported . emit ( True ) self . accept ( )
Successfully close the widget and emit an export signal .
15,468
def rejected ( self ) : self . _resetWidgets ( ) self . exported . emit ( False ) self . reject ( )
Close the widget and reset its inital state .
15,469
def stepEnabled ( self ) : if self . value ( ) > self . minimum ( ) and self . value ( ) < self . maximum ( ) : return self . StepUpEnabled | self . StepDownEnabled elif self . value ( ) <= self . minimum ( ) : return self . StepUpEnabled elif self . value ( ) >= self . maximum ( ) : return self . StepDownEnabled
Virtual function that determines whether stepping up and down is legal at any given time .
15,470
def setSingleStep ( self , singleStep ) : if not isinstance ( singleStep , int ) : raise TypeError ( "Argument is not of type int" ) self . _singleStep = abs ( singleStep ) return self . _singleStep
setter to _singleStep . converts negativ values to positiv ones .
15,471
def setMinimum ( self , minimum ) : if not isinstance ( minimum , int ) : raise TypeError ( "Argument is not of type int or long" ) self . _minimum = minimum
setter to _minimum .
15,472
def setMaximum ( self , maximum ) : if not isinstance ( maximum , int ) : raise TypeError ( "Argument is not of type int or long" ) self . _maximum = maximum
setter to _maximum .
15,473
def save_file ( self , filepath , save_as = None , keep_orig = False , ** kwargs ) : df = self . _models [ filepath ] . dataFrame ( ) kwargs [ 'index' ] = kwargs . get ( 'index' , False ) if save_as is not None : to_path = save_as else : to_path = filepath ext = os . path . splitext ( to_path ) [ 1 ] . lower ( ) if ext == ".xlsx" : kwargs . pop ( 'sep' , None ) df . to_excel ( to_path , ** kwargs ) elif ext in [ '.csv' , '.txt' ] : df . to_csv ( to_path , ** kwargs ) else : raise NotImplementedError ( "Cannot save file of type {}" . format ( ext ) ) if save_as is not None : if keep_orig is False : model = self . _models . pop ( filepath ) model . _filePath = to_path else : model = DataFrameModel ( ) model . setDataFrame ( df , copyDataFrame = True , filePath = to_path ) self . _models [ to_path ] = model
Saves a DataFrameModel to a file .
15,474
def exception_format ( ) : return "" . join ( traceback . format_exception ( sys . exc_info ( ) [ 0 ] , sys . exc_info ( ) [ 1 ] , sys . exc_info ( ) [ 2 ] ) )
Convert exception info into a string suitable for display .
15,475
def load_tk_image ( filename ) : if filename is None : return None if not os . path . isfile ( filename ) : raise ValueError ( 'Image file {} does not exist.' . format ( filename ) ) tk_image = None filename = os . path . normpath ( filename ) _ , ext = os . path . splitext ( filename ) try : pil_image = PILImage . open ( filename ) tk_image = PILImageTk . PhotoImage ( pil_image ) except : try : tk_image = tk . PhotoImage ( file = filename ) except : msg = "Cannot load {}. Check to make sure it is an image file." . format ( filename ) try : _ = PILImage except : msg += "\nPIL library isn't installed. If it isn't installed, only .gif files can be used." raise ValueError ( msg ) return tk_image
Load in an image file and return as a tk Image .
15,476
def setDataFrame ( self , dataFrame ) : if not isinstance ( dataFrame , pandas . core . frame . DataFrame ) : raise TypeError ( 'Argument is not of type pandas.core.frame.DataFrame' ) self . layoutAboutToBeChanged . emit ( ) self . _dataFrame = dataFrame self . layoutChanged . emit ( )
setter function to _dataFrame . Holds all data .
15,477
def setEditable ( self , editable ) : if not isinstance ( editable , bool ) : raise TypeError ( 'Argument is not of type bool' ) self . _editable = editable
setter to _editable . apply changes while changing dtype .
15,478
def data ( self , index , role = Qt . DisplayRole ) : if not index . isValid ( ) : return None col = index . column ( ) columnName = self . _dataFrame . columns [ index . row ( ) ] columnDtype = self . _dataFrame [ columnName ] . dtype if role == Qt . DisplayRole or role == Qt . EditRole : if col == 0 : if columnName == index . row ( ) : return index . row ( ) return columnName elif col == 1 : return SupportedDtypes . description ( columnDtype ) elif role == DTYPE_ROLE : if col == 1 : return columnDtype else : return None
Retrieve the data stored in the model at the given index .
15,479
def setData ( self , index , value , role = DTYPE_CHANGE_ROLE ) : if role != DTYPE_CHANGE_ROLE or not index . isValid ( ) : return False if not self . editable ( ) : return False self . layoutAboutToBeChanged . emit ( ) dtype = SupportedDtypes . dtype ( value ) currentDtype = np . dtype ( index . data ( role = DTYPE_ROLE ) ) if dtype is not None : if dtype != currentDtype : columnName = self . _dataFrame . columns [ index . row ( ) ] try : if dtype == np . dtype ( '<M8[ns]' ) : if currentDtype in SupportedDtypes . boolTypes ( ) : raise Exception ( "Can't convert a boolean value into a datetime value." ) self . _dataFrame [ columnName ] = self . _dataFrame [ columnName ] . apply ( pandas . to_datetime ) else : self . _dataFrame [ columnName ] = self . _dataFrame [ columnName ] . astype ( dtype ) self . dtypeChanged . emit ( index . row ( ) , dtype ) self . layoutChanged . emit ( ) return True except Exception : message = 'Could not change datatype %s of column %s to datatype %s' % ( currentDtype , columnName , dtype ) self . changeFailed . emit ( message , index , dtype ) raise return False
Updates the datatype of a column .
15,480
def search ( self ) : safeEnvDict = { 'freeSearch' : self . freeSearch , 'extentSearch' : self . extentSearch , 'indexSearch' : self . indexSearch } for col in self . _dataFrame . columns : safeEnvDict [ col ] = self . _dataFrame [ col ] try : searchIndex = eval ( self . _filterString , { '__builtins__' : None } , safeEnvDict ) except NameError : return [ ] , False except SyntaxError : return [ ] , False except ValueError : return [ ] , False except TypeError : return [ ] , False return searchIndex , True
Applies the filter to the stored dataframe .
15,481
def freeSearch ( self , searchString ) : if not self . _dataFrame . empty : question = self . _dataFrame . index == - 9999 for column in self . _dataFrame . columns : dfColumn = self . _dataFrame [ column ] dfColumn = dfColumn . apply ( str ) question2 = dfColumn . str . contains ( searchString , flags = re . IGNORECASE , regex = True , na = False ) question = np . logical_or ( question , question2 ) return question else : return [ ]
Execute a free text search for all columns in the dataframe .
15,482
def extentSearch ( self , xmin , ymin , xmax , ymax ) : if not self . _dataFrame . empty : try : questionMin = ( self . _dataFrame . lat >= xmin ) & ( self . _dataFrame . lng >= ymin ) questionMax = ( self . _dataFrame . lat <= xmax ) & ( self . _dataFrame . lng <= ymax ) return np . logical_and ( questionMin , questionMax ) except AttributeError : return [ ] else : return [ ]
Filters the data by a geographical bounding box .
15,483
def indexSearch ( self , indexes ) : if not self . _dataFrame . empty : filter0 = self . _dataFrame . index == - 9999 for index in indexes : filter1 = self . _dataFrame . index == index filter0 = np . logical_or ( filter0 , filter1 ) return filter0 else : return [ ]
Filters the data by a list of indexes .
15,484
def read_file ( filepath , ** kwargs ) : return DataFrameModel ( dataFrame = superReadFile ( filepath , ** kwargs ) , filePath = filepath )
Read a data file into a DataFrameModel .
15,485
def setDataFrame ( self , dataFrame , copyDataFrame = False , filePath = None ) : if not isinstance ( dataFrame , pandas . core . frame . DataFrame ) : raise TypeError ( "not of type pandas.core.frame.DataFrame" ) self . layoutAboutToBeChanged . emit ( ) if copyDataFrame : self . _dataFrame = dataFrame . copy ( ) else : self . _dataFrame = dataFrame self . _columnDtypeModel = ColumnDtypeModel ( dataFrame ) self . _columnDtypeModel . dtypeChanged . connect ( self . propagateDtypeChanges ) self . _columnDtypeModel . changeFailed . connect ( lambda columnName , index , dtype : self . changingDtypeFailed . emit ( columnName , index , dtype ) ) if filePath is not None : self . _filePath = filePath self . layoutChanged . emit ( ) self . dataChanged . emit ( ) self . dataFrameChanged . emit ( )
Setter function to _dataFrame . Holds all data .
15,486
def timestampFormat ( self , timestampFormat ) : if not isinstance ( timestampFormat , str ) : raise TypeError ( 'not of type unicode' ) self . _timestampFormat = timestampFormat
Setter to _timestampFormat . Formatting string for conversion of timestamps to QtCore . QDateTime
15,487
def sort ( self , columnId , order = Qt . AscendingOrder ) : self . layoutAboutToBeChanged . emit ( ) self . sortingAboutToStart . emit ( ) column = self . _dataFrame . columns [ columnId ] self . _dataFrame . sort_values ( column , ascending = not bool ( order ) , inplace = True ) self . layoutChanged . emit ( ) self . sortingFinished . emit ( )
Sorts the model column
15,488
def setFilter ( self , search ) : if not isinstance ( search , DataSearch ) : raise TypeError ( 'The given parameter must an `qtpandas.DataSearch` object' ) self . _search = search self . layoutAboutToBeChanged . emit ( ) if self . _dataFrameOriginal is not None : self . _dataFrame = self . _dataFrameOriginal self . _dataFrameOriginal = self . _dataFrame . copy ( ) self . _search . setDataFrame ( self . _dataFrame ) searchIndex , valid = self . _search . search ( ) if valid : self . _dataFrame = self . _dataFrame [ searchIndex ] self . layoutChanged . emit ( ) else : self . clearFilter ( ) self . layoutChanged . emit ( ) self . dataFrameChanged . emit ( )
Apply a filter and hide rows .
15,489
def clearFilter ( self ) : if self . _dataFrameOriginal is not None : self . layoutAboutToBeChanged . emit ( ) self . _dataFrame = self . _dataFrameOriginal self . _dataFrameOriginal = None self . layoutChanged . emit ( )
Clear all filters .
15,490
def addDataFrameColumn ( self , columnName , dtype = str , defaultValue = None ) : if not self . editable or dtype not in SupportedDtypes . allTypes ( ) : return False elements = self . rowCount ( ) columnPosition = self . columnCount ( ) newColumn = pandas . Series ( [ defaultValue ] * elements , index = self . _dataFrame . index , dtype = dtype ) self . beginInsertColumns ( QtCore . QModelIndex ( ) , columnPosition - 1 , columnPosition - 1 ) try : self . _dataFrame . insert ( columnPosition , columnName , newColumn , allow_duplicates = False ) except ValueError as e : return False self . endInsertColumns ( ) self . propagateDtypeChanges ( columnPosition , newColumn . dtype ) return True
Adds a column to the dataframe as long as the model s editable property is set to True and the dtype is supported .
15,491
def removeDataFrameRows ( self , rows ) : if not self . editable : return False if rows : position = min ( rows ) count = len ( rows ) self . beginRemoveRows ( QtCore . QModelIndex ( ) , position , position + count - 1 ) removedAny = False for idx , line in self . _dataFrame . iterrows ( ) : if idx in rows : removedAny = True self . _dataFrame . drop ( idx , inplace = True ) if not removedAny : return False self . _dataFrame . reset_index ( inplace = True , drop = True ) self . endRemoveRows ( ) return True return False
Removes rows from the dataframe .
15,492
def restore ( self ) : if not os . path . exists ( self . filename ) : return self if not os . path . isfile ( self . filename ) : return self try : with open ( self . filename , "rb" ) as f : unpickledObject = pickle . load ( f ) for key in list ( self . __dict__ . keys ( ) ) : default = self . __dict__ [ key ] self . __dict__ [ key ] = unpickledObject . __dict__ . get ( key , default ) except : pass return self
Set the values of whatever attributes are recoverable from the pickle file .
15,493
def store ( self ) : with open ( self . filename , "wb" ) as f : pickle . dump ( self , f )
Save the attributes of the EgStore object to a pickle file . Note that if the directory for the pickle file does not already exist the store operation will fail .
15,494
def buttonbox ( msg = "" , title = " " , choices = ( "Button[1]" , "Button[2]" , "Button[3]" ) , image = None , root = None , default_choice = None , cancel_choice = None ) : global boxRoot , __replyButtonText , buttonsFrame if default_choice is None : default_choice = choices [ 0 ] __replyButtonText = choices [ 0 ] if root : root . withdraw ( ) boxRoot = Toplevel ( master = root ) boxRoot . withdraw ( ) else : boxRoot = Tk ( ) boxRoot . withdraw ( ) boxRoot . title ( title ) boxRoot . iconname ( 'Dialog' ) boxRoot . geometry ( st . rootWindowPosition ) boxRoot . minsize ( 400 , 100 ) messageFrame = Frame ( master = boxRoot ) messageFrame . pack ( side = TOP , fill = BOTH ) if image : tk_Image = None try : tk_Image = ut . load_tk_image ( image ) except Exception as inst : print ( inst ) if tk_Image : imageFrame = Frame ( master = boxRoot ) imageFrame . pack ( side = TOP , fill = BOTH ) label = Label ( imageFrame , image = tk_Image ) label . image = tk_Image label . pack ( side = TOP , expand = YES , fill = X , padx = '1m' , pady = '1m' ) buttonsFrame = Frame ( master = boxRoot ) buttonsFrame . pack ( side = TOP , fill = BOTH ) messageWidget = Message ( messageFrame , text = msg , width = 400 ) messageWidget . configure ( font = ( st . PROPORTIONAL_FONT_FAMILY , st . PROPORTIONAL_FONT_SIZE ) ) messageWidget . pack ( side = TOP , expand = YES , fill = X , padx = '3m' , pady = '3m' ) __put_buttons_in_buttonframe ( choices , default_choice , cancel_choice ) boxRoot . deiconify ( ) boxRoot . mainloop ( ) boxRoot . destroy ( ) if root : root . deiconify ( ) return __replyButtonText
Display a msg a title an image and a set of buttons . The buttons are defined by the members of the choices list .
15,495
def __buttonEvent ( event = None , buttons = None , virtual_event = None ) : global boxRoot , __replyButtonText m = re . match ( "(\d+)x(\d+)([-+]\d+)([-+]\d+)" , boxRoot . geometry ( ) ) if not m : raise ValueError ( "failed to parse geometry string: {}" . format ( boxRoot . geometry ( ) ) ) width , height , xoffset , yoffset = [ int ( s ) for s in m . groups ( ) ] st . rootWindowPosition = '{0:+g}{1:+g}' . format ( xoffset , yoffset ) if virtual_event == 'cancel' : for button_name , button in list ( buttons . items ( ) ) : if 'cancel_choice' in button : __replyButtonText = button [ 'original_text' ] __replyButtonText = None boxRoot . quit ( ) return if virtual_event == 'select' : text = event . widget . config ( 'text' ) [ - 1 ] if not isinstance ( text , ut . str ) : text = ' ' . join ( text ) for button_name , button in list ( buttons . items ( ) ) : if button [ 'clean_text' ] == text : __replyButtonText = button [ 'original_text' ] boxRoot . quit ( ) return if buttons : for button_name , button in list ( buttons . items ( ) ) : hotkey_pressed = event . keysym if event . keysym != event . char : hotkey_pressed = '<{}>' . format ( event . keysym ) if button [ 'hotkey' ] == hotkey_pressed : __replyButtonText = button_name boxRoot . quit ( ) return print ( "Event not understood" )
Handle an event that is generated by a person interacting with a button . It may be a button press or a key press .
15,496
def indexbox ( msg = "Shall I continue?" , title = " " , choices = ( "Yes" , "No" ) , image = None , default_choice = 'Yes' , cancel_choice = 'No' ) : reply = bb . buttonbox ( msg = msg , title = title , choices = choices , image = image , default_choice = default_choice , cancel_choice = cancel_choice ) if reply is None : return None for i , choice in enumerate ( choices ) : if reply == choice : return i msg = ( "There is a program logic error in the EasyGui code " "for indexbox.\nreply={0}, choices={1}" . format ( reply , choices ) ) raise AssertionError ( msg )
Display a buttonbox with the specified choices .
15,497
def msgbox ( msg = "(Your message goes here)" , title = " " , ok_button = "OK" , image = None , root = None ) : if not isinstance ( ok_button , ut . str ) : raise AssertionError ( "The 'ok_button' argument to msgbox must be a string." ) return bb . buttonbox ( msg = msg , title = title , choices = [ ok_button ] , image = image , root = root , default_choice = ok_button , cancel_choice = ok_button )
Display a message box
15,498
def multenterbox ( msg = "Fill in values for the fields." , title = " " , fields = ( ) , values = ( ) ) : r return bb . __multfillablebox ( msg , title , fields , values , None )
r Show screen with multiple data entry fields .
15,499
def exceptionbox ( msg = None , title = None ) : if title is None : title = "Error Report" if msg is None : msg = "An error (exception) has occurred in the program." codebox ( msg , title , ut . exception_format ( ) )
Display a box that gives information about an exception that has just been raised .