Setup DataFrameEditor:
        return False if data is not supported, True otherwise.
        Supported types for data are DataFrame, Series and Index.
359648
def setup_and_check(self, data, title=''):
        
        self._selection_rec = False
        self._model = None

        self.layout = QGridLayout()
        self.layout.setSpacing(0)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.layout)
        self.setWindowIcon(ima.icon('arredit'))
        if title:
            title = to_text_string(title) + " - %s" % data.__class__.__name__
        else:
            title = _("%s editor") % data.__class__.__name__
        if isinstance(data, Series):
            self.is_series = True
            data = data.to_frame()
        elif isinstance(data, Index):
            data = DataFrame(data)

        self.setWindowTitle(title)
        self.resize(600, 500)

        self.hscroll = QScrollBar(Qt.Horizontal)
        self.vscroll = QScrollBar(Qt.Vertical)

        # Create the view for the level
        self.create_table_level()

        # Create the view for the horizontal header
        self.create_table_header()

        # Create the view for the vertical index
        self.create_table_index()

        # Create the model and view of the data
        self.dataModel = DataFrameModel(data, parent=self)
        self.dataModel.dataChanged.connect(self.save_and_close_enable)
        self.create_data_table()

        self.layout.addWidget(self.hscroll, 2, 0, 1, 2)
        self.layout.addWidget(self.vscroll, 0, 2, 2, 1)

        # autosize columns on-demand
        self._autosized_cols = set()
        self._max_autosize_ms = None
        self.dataTable.installEventFilter(self)

        avg_width = self.fontMetrics().averageCharWidth()
        self.min_trunc = avg_width * 12  # Minimum size for columns
        self.max_width = avg_width * 64  # Maximum size for columns

        self.setLayout(self.layout)
        self.setMinimumSize(400, 300)
        # Make the dialog act as a window
        self.setWindowFlags(Qt.Window)
        btn_layout = QHBoxLayout()

        btn = QPushButton(_("Format"))
        # disable format button for int type
        btn_layout.addWidget(btn)
        btn.clicked.connect(self.change_format)
        btn = QPushButton(_('Resize'))
        btn_layout.addWidget(btn)
        btn.clicked.connect(self.resize_to_contents)

        bgcolor = QCheckBox(_('Background color'))
        bgcolor.setChecked(self.dataModel.bgcolor_enabled)
        bgcolor.setEnabled(self.dataModel.bgcolor_enabled)
        bgcolor.stateChanged.connect(self.change_bgcolor_enable)
        btn_layout.addWidget(bgcolor)

        self.bgcolor_global = QCheckBox(_('Column min/max'))
        self.bgcolor_global.setChecked(self.dataModel.colum_avg_enabled)
        self.bgcolor_global.setEnabled(not self.is_series and
                                       self.dataModel.bgcolor_enabled)
        self.bgcolor_global.stateChanged.connect(self.dataModel.colum_avg)
        btn_layout.addWidget(self.bgcolor_global)

        btn_layout.addStretch()

        self.btn_save_and_close = QPushButton(_('Save and Close'))
        self.btn_save_and_close.setDisabled(True)
        self.btn_save_and_close.clicked.connect(self.accept)
        btn_layout.addWidget(self.btn_save_and_close)

        self.btn_close = QPushButton(_('Close'))
        self.btn_close.setAutoDefault(True)
        self.btn_close.setDefault(True)
        self.btn_close.clicked.connect(self.reject)
        btn_layout.addWidget(self.btn_close)

        btn_layout.setContentsMargins(4, 4, 4, 4)
        self.layout.addLayout(btn_layout, 4, 0, 1, 2)
        self.setModel(self.dataModel)
        self.resizeColumnsToContents()

        return True
149744
def should_series_dispatch(left, right, op):
    
    if left._is_mixed_type or right._is_mixed_type:
        return True

    if not len(left.columns) or not len(right.columns):
        # ensure obj.dtypes[0] exists for each obj
        return False

    ldtype = left.dtypes.iloc[0]
    rdtype = right.dtypes.iloc[0]

    if ((is_timedelta64_dtype(ldtype) and is_integer_dtype(rdtype)) or
            (is_timedelta64_dtype(rdtype) and is_integer_dtype(ldtype))):
        # numpy integer dtypes as timedelta64 dtypes in this scenario
        return True

    if is_datetime64_dtype(ldtype) and is_object_dtype(rdtype):
        # in particular case where right is an array of DateOffsets
        return True

    return False
11371
def _construct_df(pdb_lines):
        """"""
        valids = tuple(pdb_records.keys())
        line_lists = {r: [] for r in valids}
        line_lists['OTHERS'] = []
        for line_num, line in enumerate(pdb_lines):
            if line.strip():
                if line.startswith(valids):
                    record = line[:6].rstrip()
                    line_ele = ['' for _ in range(len(
                        pdb_records[record]) + 1)]
                    for idx, ele in enumerate(pdb_records[record]):
                        line_ele[idx] = (line[ele['line'][0]:ele['line'][1]]
                                         .strip())
                    line_ele[-1] = line_num
                    line_lists[record].append(line_ele)
                else:
                    line_lists['OTHERS'].append([line[:6].rstrip(),
                                                line[6:-1].rstrip(), line_num])

        dfs = {}
        for r in line_lists.items():
            df = pd.DataFrame(r[1], columns=[c['id'] for c in
                                             pdb_records[r[0]]] + ['line_idx'])
            for c in pdb_records[r[0]]:
                try:
                    df[c['id']] = df[c['id']].astype(c['type'])
                except ValueError:
                    # expect ValueError if float/int columns are empty strings
                    df[c['id']] = pd.Series(np.nan, index=df.index)

            dfs[r[0]] = df
        return dfs
944669
def get_default_pandas_converters() -> List[Union[Converter[Any, pd.DataFrame],
                                                  Converter[pd.DataFrame, Any]]]:
    
    return [ConverterFunction(from_type=pd.DataFrame, to_type=dict, conversion_method=single_row_or_col_df_to_dict),
            ConverterFunction(from_type=dict, to_type=pd.DataFrame, conversion_method=dict_to_df,
                              option_hints=dict_to_single_row_or_col_df_opts),
            ConverterFunction(from_type=pd.DataFrame, to_type=pd.Series,
                              conversion_method=single_row_or_col_df_to_series)]
743351
def add_table(self, dataframe, isStyled = False):
        """"""

        if isStyled :
            table_string = dataframe.render()
        else :
            table_string = dataframe.style.render()
            
        table_string = table_string.replace("\n", "").replace("<table", """<table class = "table table-sm table-hover" """).replace("<thead>", """<thead class="thead-inverse">""")
        self.table = table_string
660783
def data_type(self, data_type):
        
        allowed_values = ["string", "number", "date", "color"]
        if data_type is not None and data_type not in allowed_values:
            raise ValueError(
                "Invalid value for `data_type` ({0}), must be one of {1}"
                .format(data_type, allowed_values)
            )

        self._data_type = data_type
638637
def _convert_types(self, filename: str, df: pd.DataFrame) -> None:
        
        if df.empty:
            return

        converters = self._config.nodes.get(filename, {}).get("converters", {})
        for col, converter in converters.items():
            if col in df.columns:
                df[col] = converter(df[col])
897327
def _index_into(self, idx, data):
        
        try:
            if is_dataframe(data):
                # Assume column indexing
                return data[idx]
            # Otherwise assume numpy array-like indexing
            return data[:,idx]
        except Exception as e:
            raise IndexError(
                "could not index column '{}' into type {}: {}".format(
                    self.columns, data.__class__.__name__, e
            ))
551395
def prepare(self, data_source):
        
        dataframe = self.__get_dataframe(data_source, use_target=True)
        self.__config.get_data_model().set_features_types_from_dataframe(dataframe)
        dataframe = self.__cleaner.prepare(dataframe)
        return self.__transformer.prepare(dataframe)
1305196
def is_dataframe(obj):
    
    try:
        # This is the best method of type checking
        from pandas import DataFrame
        return isinstance(obj, DataFrame)
    except ImportError:
        # Pandas is not a dependency, so this is scary
        return obj.__class__.__name__ == "DataFrame"
990319
def is_dataframe(data):
    
    dd = None
    if 'dask' in sys.modules and 'pandas' in sys.modules:
        import dask.dataframe as dd
    return((pd is not None and isinstance(data, pd.DataFrame)) or
          (dd is not None and isinstance(data, dd.DataFrame)))
148222
def set_columns(self, types):
        
        if self._types:
            raise wandb.Error('TypedTable.set_columns called more than once.')
        try:
            for key, type_ in types:
                if type_ not in TYPE_TO_TYPESTRING:
                    raise wandb.Error('TypedTable.set_columns received invalid type ({}) for key "{}".\n  Valid types: {}'.format(
                        type_, key, '[%s]' % ', '.join(VALID_TYPE_NAMES)))
        except TypeError:
            raise wandb.Error(
                'TypedTable.set_columns requires iterable of (column_name, type) pairs.')
        self._types = dict(types)
        self._output.add({
            'typemap': {k: TYPE_TO_TYPESTRING[type_] for k, type_ in types},
            'columns': [t[0] for t in types]})
92416
def accepted(self):
        
        model = self._previewTableView.model()
        if model is not None:
            df = model.dataFrame().copy()
            dfModel = DataFrameModel(df)
            self.load.emit(dfModel, self._filename)
            print(("Emitted model for {}".format(self._filename)))
        self._resetWidgets()
        self.accept()
1287598
def add_data_set(self, data, series_type="map", name=None, is_coordinate = False, **kwargs):
        
        
        self.data_set_count += 1
        if not name:
            name = "Series %d" % self.data_set_count
        kwargs.update({'name':name})

        if is_coordinate:
            self.data_is_coordinate = True
            self.add_JSsource('https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.6/proj4.js')
            if self.map and not self.data_temp:
                series_data = Series([], series_type='map', **{'mapData': self.map})
                series_data.__options__().update(SeriesOptions(series_type='map', **{'mapData': self.map}).__options__())
                self.data_temp.append(series_data)

        if self.map and 'mapData' in kwargs.keys():
            kwargs.update({'mapData': self.map})

        series_data = Series(data, series_type=series_type, **kwargs)
       
        series_data.__options__().update(SeriesOptions(series_type=series_type, **kwargs).__options__())
        self.data_temp.append(series_data)
1370952
def apply(self, df):
        
        if hasattr(self.definition, '__call__'):
            r = self.definition(df)
        elif self.definition in df.columns:
            r = df[self.definition]
        elif not isinstance(self.definition, string_types):
            r = pd.Series(self.definition, index=df.index)
        else:
            raise ValueError("Invalid column definition: %s" % str(self.definition))
        return r.astype(self.astype) if self.astype else r
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
603107
def setColumnType( self, columnType ):
        
        if ( columnType == self._columnType ):
            return False
        
        self._columnType = columnType
        self.rebuild()
        return True