Create a pandas coordinates dataframe from the lines in the specified chain.
494962
def extract_xyz_matrix_from_chain(self, chain_id, atoms_of_interest = []):
        ''''''
        chains = [l[21] for l in self.structure_lines if len(l) > 21]
        chain_lines = [l for l in self.structure_lines if len(l) > 21 and l[21] == chain_id]
        return PDB.extract_xyz_matrix_from_pdb(chain_lines, atoms_of_interest = atoms_of_interest, include_all_columns = True)
711624
def build_conversion_table(self, dataframes):
        
        self.data = pd.DataFrame(dataframes)
        tmp_pairs = [s.split("/") for s in self.data.columns]
        self.data.columns = pd.MultiIndex.from_tuples(tmp_pairs)
85378
def get_dataframes():
    """"""

    for k, v in caller_locals().items():
        if k.startswith('_'):
            continue

        if isinstance(v, pd.core.frame.DataFrame):
            yield k, v
545661
def from_lines(lines: Iterable[str], **kwargs) -> BELGraph:
    
    graph = BELGraph()
    parse_lines(graph=graph, lines=lines, **kwargs)
    return graph
381833
def read_coordinates(self, where=None, start=None, stop=None, **kwargs):
        

        # validate the version
        self.validate_version(where)

        # infer the data kind
        if not self.infer_axes():
            return False

        # create the selection
        self.selection = Selection(
            self, where=where, start=start, stop=stop, **kwargs)
        coords = self.selection.select_coords()
        if self.selection.filter is not None:
            for field, op, filt in self.selection.filter.format():
                data = self.read_column(
                    field, start=coords.min(), stop=coords.max() + 1)
                coords = coords[
                    op(data.iloc[coords - coords.min()], filt).values]

        return Index(coords)
600509
def from_coords(cls, coords, sort=True):
        
        coords = list(coords)
        if sort:
            coords.sort()
        if len(coords[0]) == 2:  # 2D coordinates
            lons, lats = zip(*coords)
            depths = None
        else:  # 3D coordinates
            lons, lats, depths = zip(*coords)
            depths = numpy.array(depths)
        return cls(numpy.array(lons), numpy.array(lats), depths)
1203494
def _read(cls, **kwargs):
        
        pd_obj = pandas.read_csv(**kwargs)
        if isinstance(pd_obj, pandas.DataFrame):
            return cls.from_pandas(pd_obj)
        if isinstance(pd_obj, pandas.io.parsers.TextFileReader):
            # Overwriting the read method should return a ray DataFrame for calls
            # to __next__ and get_chunk
            pd_read = pd_obj.read
            pd_obj.read = lambda *args, **kwargs: cls.from_pandas(
                pd_read(*args, **kwargs)
            )
        return pd_obj
1161798
def _make_df(rows):
    """"""

    # Make DataFrame
    df = pd.DataFrame(rows).set_index('ts')

    # TimeDelta Support: https://issues.apache.org/jira/browse/ARROW-835
    for column in df.columns:
        if(df[column].dtype == 'timedelta64[ns]'):
            print('Converting timedelta column {:s}...'.format(column))
            df[column] = df[column].astype(str)
    return df
320124
def _dendropy_to_dataframe(
    tree,
    add_node_labels=True,
    use_uids=True):
    """"""
    # Maximum distance from root.
    tree.max_distance_from_root()

    # Initialize the data object.
    idx = []
    data = {
        'type': [],
        'id': [],
        'parent': [],
        'length': [],
        'label': [],
        'distance': []}

    if use_uids:
        data['uid'] = []

    # Add labels to internal nodes if set to true.
    if add_node_labels:
        for i, node in enumerate(tree.internal_nodes()):
            node.label = str(i)

    for node in tree.nodes():
        # Get node type
        if node.is_leaf():
            type_ = 'leaf'
            label = str(node.taxon.label).replace(' ', '_')
        elif node.is_internal():
            type_ = 'node'
            label = str(node.label)

        # Set node label and parent.
        id_ = label
        parent_node = node.parent_node
        length = node.edge_length
        distance = node.distance_from_root()

        # Is this node a root?
        if parent_node is None and length is None:
            parent_label = None
            parent_node = None
            length = 0
            distance = 0
            type_ = 'root'

        # Set parent node label
        elif parent_node.is_internal():
            parent_label = str(parent_node.label)

        else:
            raise Exception("Subtree is not attached to tree?")

        # Add this node to the data.
        data['type'].append(type_)
        data['id'].append(id_)
        data['parent'].append(parent_label)
        data['length'].append(length)
        data['label'].append(label)
        data['distance'].append(distance)

        if use_uids:
            data['uid'].append(get_random_id(10))

    # Construct dataframe.
    df = pandas.DataFrame(data)
    return df
1285643
def merge_coords(objs, compat='minimal', join='outer', priority_arg=None,
                 indexes=None):
    
    _assert_compat_valid(compat)
    coerced = coerce_pandas_values(objs)
    aligned = deep_align(coerced, join=join, copy=False, indexes=indexes)
    expanded = expand_variable_dicts(aligned)
    priority_vars = _get_priority_vars(aligned, priority_arg, compat=compat)
    variables = merge_variables(expanded, priority_vars, compat=compat)
    assert_unique_multiindex_level_names(variables)

    return variables
661978
def run(self, lines):
        """"""
        ret = []

        for block in self.blocks(lines):
            ret.extend(self.convert_table(block))

        return ret
1043742
def write_dataframe(self, result, dst_paths, nodata=None, compress='lzw'):
        """"""
        result = self._convert_to_ndarray(result)
        self.write_ndarray(result, dst_paths, nodata=nodata, compress=compress)
1010571
def make_dataframe(obj, columns=None, exclude=None, limit=1e8):
    """"""
    try:
        obj = obj.objects.all()[:limit]
    except:
        pass
    if isinstance(obj, (pd.Series, list, tuple)):
        return make_dataframe(pd.DataFrame(obj), columns, exclude, limit)
    # if the obj is a named tuple, DataFrame, dict of columns, django QuerySet, sql alchemy query result
    # retrieve the "include"d field/column names from its keys/fields/attributes
    if columns is None:
        columns = get_column_labels(obj)
    if exclude is not None and columns is not None and columns and exclude:
        columns = [i for i in columns if i not in exclude]
    try:
        return pd.DataFrame(list(obj.values(*columns)[:limit]))
    except:
        pass
    try:
        return pd.DataFrame(obj)[fuzzy_get(obj, columns)]
    except:
        pass
    return pd.DataFrame(obj)
1067240
def _unpack_dataframes(dfs):
    
    col_groups = defaultdict(list)
    columns = dfs[0].columns
    for col in columns:
        key, *loc = col.split(".")
        loc = tuple(int(i) - 1 for i in loc)
        col_groups[key].append((col, loc))

    chains = len(dfs)
    draws = len(dfs[0])
    sample = {}
    for key, cols_locs in col_groups.items():
        ndim = np.array([loc for _, loc in cols_locs]).max(0) + 1
        sample[key] = np.full((chains, draws, *ndim), np.nan)
        for col, loc in cols_locs:
            for chain_id, df in enumerate(dfs):
                draw = df[col].values
                if loc == ():
                    sample[key][chain_id, :] = draw
                else:
                    axis1_all = range(sample[key].shape[1])
                    slicer = (chain_id, axis1_all, *loc)
                    sample[key][slicer] = draw
    return sample
261033
def from_df(cls, path, df:DataFrame, dep_var:str, valid_idx:Collection[int], procs:OptTabTfms=None,
                cat_names:OptStrList=None, cont_names:OptStrList=None, classes:Collection=None, 
                test_df=None, bs:int=64, val_bs:int=None, num_workers:int=defaults.cpus, dl_tfms:Optional[Collection[Callable]]=None, 
                device:torch.device=None, collate_fn:Callable=data_collate, no_check:bool=False)->DataBunch:
        ""
        cat_names = ifnone(cat_names, []).copy()
        cont_names = ifnone(cont_names, list(set(df)-set(cat_names)-{dep_var}))
        procs = listify(procs)
        src = (TabularList.from_df(df, path=path, cat_names=cat_names, cont_names=cont_names, procs=procs)
                           .split_by_idx(valid_idx))
        src = src.label_from_df(cols=dep_var) if classes is None else src.label_from_df(cols=dep_var, classes=classes)
        if test_df is not None: src.add_test(TabularList.from_df(test_df, cat_names=cat_names, cont_names=cont_names,
                                                                 processor = src.train.x.processor))
        return src.databunch(path=path, bs=bs, val_bs=val_bs, num_workers=num_workers, device=device, 
                             collate_fn=collate_fn, no_check=no_check)
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)
936211
def graph_from_cov_df(df, threshold=.5, gain=2., n=None, class_dict=CLASSES):
    """"""
    n = n or len(df)
    nodes = [{'group': class_dict.get(name, 0), "name": name} for name in df.index.values][:n]
    edges = []
    for i, (row_name, row) in enumerate(df.iterrows()):
        for j, value in enumerate(row.values):
            if i > j and value * gain > threshold and i < n and j < n:
                edges += [{'source': i, 'target': j, 'value': gain * value}]
    return nodes, edges