Create Pandas DataFrame from TimeSeries object.
    Use: Must first extractTs to get a time series. Then pick one item from time series and pass it through

    :param dict tso: Time series entry
    :return dict dfs: Pandas dataframes
485439
def tsToDf(tso):
    
    dfs = {}
    try:
        dfs = ts_to_df(tso)
    except Exception as e:
        print("Error: Unable to create data frame")
        logger_start.warn("ts_to_df: tso malformed: {}".format(e))
    return dfs
1000608
def to_excel(self, *args):
        
        path = os.getcwd()
        fname = self.fname.replace(".tpl", "_tpl") + ".xlsx"
        idxs = self.filter_trends("")
        for idx in idxs:
            self.extract(idx)
        data_df = pd.DataFrame(self.data)
        data_df.columns = self.label.values()
        data_df.insert(0, "Time [s]", self.time)
        if len(args) > 0 and args[0] != "":
            path = args[0]
            if os.path.exists(path) == False:
                os.mkdir(path)
            data_df.to_excel(path + os.sep + fname)
        else:
            data_df.to_excel(self.path + os.sep + fname)
791042
def _extract_columns(d, tmp_tso, pc):
    
    logger_ts.info("enter extract_columns")
    for k, v in d.items():
        if isinstance(v, dict):
            flat_data = _extract_nested(pc + "_" + k, v, {})
            for n,m in flat_data.items():
                tmp_tso[n] = m
        else:
            # Assume if it's not a special nested case, then it's a string value
            tmp_tso[pc + '_' + k] = v
    return tmp_tso
872446
def query_timeseries(self, query, from_time=None, to_time=None, by_post=False):
    
    return timeseries.query_timeseries(self, query, from_time, to_time, by_post=by_post)
839524
def transform_timeseries4pypsa(timeseries, timerange, column=None):
    
    timeseries.index = [str(i) for i in timeseries.index]

    if column is None:
        pypsa_timeseries = timeseries.apply(
            Series).transpose().set_index(timerange)
    else:
        pypsa_timeseries = timeseries[column].apply(
            Series).transpose().set_index(timerange)

    return pypsa_timeseries
1255693
def dataframe(self):
        """"""

        if self._dataframe is None:
            try:
                import pandas as pd
            except ImportError:
                raise RuntimeError('To enable dataframe support, '
                                   'run \'pip install datadotworld[pandas]\'')

            self._dataframe = pd.DataFrame.from_records(self._iter_rows(),
                                                        coerce_float=True)

        return self._dataframe
942348
def tcounts(self):
        
        df = pd.DataFrame([[t.name(), t.size()] for t in self.tables()], columns=["name", "size"])
        df.index = df.name
        return df
385494
def to_pandas(self):
        
        from pandas import DataFrame as PandasDataFrame

        pandas_index = self.index.to_pandas()
        pandas_data = OrderedDict((column.name, column.to_pandas())
                                  for column in self._iter())

        return PandasDataFrame(pandas_data, pandas_index)
120109
def to_series(self):
        
        return pandas.Series(
            self.cdf, index=[numpy.nan] + list(self.bin_edges) + [numpy.nan])
227328
def from_pandas(cls, series):
        
        from pandas import Index as PandasIndex, MultiIndex as PandasMultiIndex

        if isinstance(series.index, PandasIndex):
            baloo_index = Index.from_pandas(series.index)
        elif isinstance(series.index, PandasMultiIndex):
            baloo_index = MultiIndex.from_pandas(series.index)
        else:
            raise TypeError('Cannot convert pandas index of type={} to baloo'.format(type(series.index)))

        return _series_from_pandas(series, baloo_index)
16810
def _join_factory(cls, gap, pad):
    
    if issubclass(cls, dict):
        def _join(data):
            out = cls()
            data = list(data)
            while data:
                tsd = data.pop(0)
                out.append(tsd, gap=gap, pad=pad)
                del tsd
            return out
    else:
        from .. import TimeSeriesBaseList

        def _join(arrays):
            list_ = TimeSeriesBaseList(*arrays)
            return list_.join(pad=pad, gap=gap)
    return _join
1156427
def has_data_for_dates(series_or_df, first_date, last_date):
    
    dts = series_or_df.index
    if not isinstance(dts, pd.DatetimeIndex):
        raise TypeError("Expected a DatetimeIndex, but got %s." % type(dts))
    first, last = dts[[0, -1]]
    return (first <= first_date) and (last >= last_date)
1029508
def _add_series_or_dataframe_operations(cls):
        

        from pandas.core import window as rwindow

        @Appender(rwindow.rolling.__doc__)
        def rolling(self, window, min_periods=None, center=False,
                    win_type=None, on=None, axis=0, closed=None):
            axis = self._get_axis_number(axis)
            return rwindow.rolling(self, window=window,
                                   min_periods=min_periods,
                                   center=center, win_type=win_type,
                                   on=on, axis=axis, closed=closed)

        cls.rolling = rolling

        @Appender(rwindow.expanding.__doc__)
        def expanding(self, min_periods=1, center=False, axis=0):
            axis = self._get_axis_number(axis)
            return rwindow.expanding(self, min_periods=min_periods,
                                     center=center, axis=axis)

        cls.expanding = expanding

        @Appender(rwindow.ewm.__doc__)
        def ewm(self, com=None, span=None, halflife=None, alpha=None,
                min_periods=0, adjust=True, ignore_na=False,
                axis=0):
            axis = self._get_axis_number(axis)
            return rwindow.ewm(self, com=com, span=span, halflife=halflife,
                               alpha=alpha, min_periods=min_periods,
                               adjust=adjust, ignore_na=ignore_na, axis=axis)

        cls.ewm = ewm
1122869
def get_df(self, query_obj=None):
        """"""
        if not query_obj:
            query_obj = self.query_obj()
        if not query_obj:
            return None

        self.error_msg = ''

        timestamp_format = None
        if self.datasource.type == 'table':
            dttm_col = self.datasource.get_col(query_obj['granularity'])
            if dttm_col:
                timestamp_format = dttm_col.python_date_format

        # The datasource here can be different backend but the interface is common
        self.results = self.datasource.query(query_obj)
        self.query = self.results.query
        self.status = self.results.status
        self.error_message = self.results.error_message

        df = self.results.df
        # Transform the timestamp we received from database to pandas supported
        # datetime format. If no python_date_format is specified, the pattern will
        # be considered as the default ISO date format
        # If the datetime format is unix, the parse will use the corresponding
        # parsing logic.
        if df is not None and not df.empty:
            if DTTM_ALIAS in df.columns:
                if timestamp_format in ('epoch_s', 'epoch_ms'):
                    # Column has already been formatted as a timestamp.
                    dttm_col = df[DTTM_ALIAS]
                    one_ts_val = dttm_col[0]

                    # convert time column to pandas Timestamp, but different
                    # ways to convert depending on string or int types
                    try:
                        int(one_ts_val)
                        is_integral = True
                    except ValueError:
                        is_integral = False
                    if is_integral:
                        unit = 's' if timestamp_format == 'epoch_s' else 'ms'
                        df[DTTM_ALIAS] = pd.to_datetime(dttm_col, utc=False, unit=unit,
                                                        origin='unix')
                    else:
                        df[DTTM_ALIAS] = dttm_col.apply(pd.Timestamp)
                else:
                    df[DTTM_ALIAS] = pd.to_datetime(
                        df[DTTM_ALIAS], utc=False, format=timestamp_format)
                if self.datasource.offset:
                    df[DTTM_ALIAS] += timedelta(hours=self.datasource.offset)
                df[DTTM_ALIAS] += self.time_shift

            if self.enforce_numerical_metrics:
                self.df_metrics_to_num(df)

            df.replace([np.inf, -np.inf], np.nan, inplace=True)
        return df
1038590
def to_df(self)->None:
        ""
        return pd.DataFrame(dict(x=self.x._relative_item_paths(), y=[str(o) for o in self.y]))
572938
def make_dataframe(result):
    
    import pandas as pd
    ret = {}
    if isinstance(result,dict):
        if 'timeseries' in result:
            result = result['timeseries']
    for uuid, data in result.items():
        df = pd.DataFrame(data)
        if len(df.columns) == 5: # statistical data
            df.columns = ['time','min','mean','max','count']
        else:
            df.columns = ['time','value']
        df['time'] = pd.to_datetime(df['time'],unit='ns')
        df = df.set_index(df.pop('time'))
        ret[uuid] = df
    return ret
505939
def create_dataframe(ensemble):
    
    logger_dataframes.info("enter ens_to_df")
    # "Flatten" the nested lists. Bring all nested lists up to top-level. Output looks like [ [1,2], [1,2], ... ]
    ll = unwrap_arrays(ensemble)
    # Check that list lengths are all equal
    valid = match_arr_lengths(ll)
    if valid:
        # Lists are equal lengths, create the dataframe
        df = pd.DataFrame(ll)
    else:
        # Lists are unequal. Print error and return nothing.
        df = "empty"
        print("Error: Numpy Array lengths do not match. Cannot create data frame")
    logger_dataframes.info("exit ens_to_df")
    return df