def sort(self, column_name): """ Sorts the data frame by the specified column. Parameters ---------- column_name: string Column name to sort Returns ------- sort: DFTrack DFTrack sorted """ if isinstance(column_name, list): for column in column_name: if column not in self.df: raise TrackException('Column name not found', "'%s'" % column) else: if column_name not in self.df: raise TrackException('Column name not found', "'%s'" % column_name) return self.__class__(self.df.sort_values(column_name), list(self.df))
def readGPXFile(self, filename): try: with open(filename, "r") as f: prev_point = None head, tail = os.path.split(filename) code_route = tail.replace(".gpx", "") try: gpx = gpxpy.parse(f) for point in gpx.walk(only_points=True): speed = point.speed_between(prev_point) if speed is None: speed = 0 timeDifference = point.time_difference(prev_point) if timeDifference is None: timeDifference = 0 distance = point.distance_3d(prev_point) if not distance: distance = point.distance_2d(prev_point) if distance is None: distance = 0 self.points_list.append([ code_route, point.latitude, point.longitude, point.elevation, point.time, speed, timeDifference, distance, gpx.name ]) prev_point = point except Exception as e: raise TrackException( 'GPX file "' + filename + '" malformed', e) except FileNotFoundError as e: raise TrackException('GPX file "' + filename + '" not found', e)
def concat(self, dfTrack): """ Concatenate DFTrack objects with 'self' Parameters ---------- dfTrack: DFTrack or list of DFTrack The ones that will be joined with 'self' Returns ------- df_concat: DFTrack A DFTrack with the all the DFTrack concatenated """ if not isinstance(dfTrack, list): # If it is not a list of DFTrack, make a list of one element dfTrack = [dfTrack] df_concat = [self.df] # First element is 'self' # From list of 'dfTrack', create a list of their dataframes for df in dfTrack: if not isinstance(df, DFTrack): raise TrackException("Parameter must be a 'DFTrack' object", '%s found' % type(df)) df_concat.append(df.df) return self.__class__(pd.concat(df_concat))
def setColors(self, column_name, individual_tracks=True): if column_name not in self.df: raise TrackException('Column name not found', "'%s'" % column_name) df = self.df.copy() df_colors = pd.DataFrame() if individual_tracks: grouped = df['CodeRoute'].unique() for name in grouped: df_slice = df[df['CodeRoute'] == name] df_slice = df_slice.reset_index(drop=True) min = df_slice[column_name].min() max = df_slice[column_name].max() df_slice['Color'] = df_slice[column_name].apply(trk_utils.rgb, minimum=min, maximum=max) df_colors = pd.concat([df_colors, df_slice]) df_colors = df_colors.reset_index(drop=True) return self.__class__(df_colors, list(df_colors)) else: min = df[column_name].min() max = df[column_name].max() df['Color'] = df[column_name].apply(trk_utils.rgb, minimum=min, maximum=max) df = df.reset_index(drop=True) return self.__class__(df, list(df))
def readCSV(self): try: return DFTrack( pd.read_csv(self.directory_or_file, sep=',', header=0, index_col=0)) except FileNotFoundError as e: raise TrackException('CSV file not found', e)
def sort(self, column_name): """ Sorts the data frame by the specified column. :param column_name: Column name to sort :type column_name: string_or_list :return: DFTrack sorted :rtype: DFTrack """ if isinstance(column_name, list): for column in column_name: if column not in self.df: raise TrackException('Column name not found', "'%s'" % column) else: if column_name not in self.df: raise TrackException('Column name not found', "'%s'" % column_name) return self.__class__(self.df.sort_values(column_name), list(self.df))
def makeMap(self, linewidth=2.5, output_file='map'): for axarr in self.axarr: axarr.lines = [] if self.map: raise TrackException('Map background found in the figure', 'Remove it to create an interactive HTML map.') if 'Color' in self.track_df.df: for point, next_point in self.computePoints(linewidth=linewidth): pass else: self.computeTracks(linewidth=linewidth) mplleaflet.save_html(fig=self.fig, tiles='esri_aerial', fileobj=output_file + '.html')#, close_mpl=False) # Creating html map
def export(self, filename='exported_file', export_format='csv'): """ Export a data frame of DFTrack to JSON or CSV. Parameters ---------- export_format: string Format to export: JSON or CSV filename: string Name of the exported file """ if export_format.lower() == 'json': self.df.reset_index().to_json(orient='records', path_or_buf=filename + '.json') elif export_format.lower() == 'csv': self.df.to_csv(path_or_buf=filename + '.csv') else: raise TrackException('Must specify a valid format to export', "'%s'" % export_format)
def getTracksByDate(self, start=None, end=None, periods=None, freq='D'): """ Gets the points of the specified date range using various combinations of parameters. 2 of 'start', 'end', or 'periods' must be specified. Date format recommended: 'yyyy-mm-dd' Parameters ---------- start: date Date start period end: date Date end period periods: int Number of periods. If None, must specify 'start' and 'end' freq: string Frequency of the date range Returns ------- df_date: DFTrack A DFTrack with the points of the specified date range. """ if trk_utils.isTimeFormat(start) or trk_utils.isTimeFormat(end): raise TrackException('Must specify an appropiate date format', 'Time format found') rng = pd.date_range(start=start, end=end, periods=periods, freq=freq) df_date = self.df.copy() df_date['Date'] = pd.to_datetime(df_date['Date']) df_date['ShortDate'] = df_date['Date'].apply( lambda date: date.date().strftime('%Y-%m-%d')) df_date = df_date[df_date['ShortDate'].apply(lambda date: date in rng)] del df_date['ShortDate'] df_date = df_date.reset_index(drop=True) return self.__class__(df_date, list(df_date))
def getTracksByTime(self, start, end, include_start=True, include_end=True): """ Gets the points between the specified time range. Parameters ---------- start: datetime.time Time start period end: datetime.time Time end period include_start: boolean include_end: boolean Returns ------- df_time: DFTrack A DFTrack with the points of the specified date and time periods. """ if not trk_utils.isTimeFormat(start) or not trk_utils.isTimeFormat( end): raise TrackException('Must specify an appropiate time format', trk_utils.TIME_FORMATS) df_time = self.df.copy() index = pd.DatetimeIndex(df_time['Date']) df_time = df_time.iloc[index.indexer_between_time( start_time=start, end_time=end, include_start=include_start, include_end=include_end)] df_time = df_time.reset_index(drop=True) return self.__class__(df_time, list(df_time))