Ejemplo n.º 1
0
    def headerData(self, section, orientation, role=Qt.DisplayRole):
        """Set header data"""
        if role != Qt.DisplayRole:
            return to_qvariant()

        if orientation == Qt.Horizontal:
            if section == 0:
                return 'Index'
            elif section == 1 and PY2:
                header = self.df_header[0]
                # Get rid of possible BOM utf-8 data present at the
                # beginning of a file, which gets attached to the first
                # column header when headers are present in the first
                # row.
                # Fixes Issue 2514
                try:
                    header = to_text_string(header, encoding='utf-8-sig')
                except:
                    # Don't perform any conversion on strings because it
                    # leads to differences between the data present in
                    # the dataframe and what is shown by Spyder
                    if not is_type_text_string(header):
                        header = to_text_string(header)
                return to_qvariant(header)
            elif is_type_text_string(self.df_header[section - 1]):
                # Don't perform any conversion on strings because it
                # leads to differences between the data present in
                # the dataframe and what is shown by Spyder
                return to_qvariant(self.df_header[section - 1])
            else:
                return to_qvariant(to_text_string(self.df_header[section - 1]))
        else:
            return to_qvariant()
Ejemplo n.º 2
0
    def data(self, index, role):
        """
        Get the data for the header.

        This is used when a header has levels.
        """
        if not index.isValid() or \
           index.row() >= self._shape[0] or \
           index.column() >= self._shape[1]:
            return None
        row, col = ((index.row(), index.column()) if self.axis == 0 else
                    (index.column(), index.row()))
        if role == Qt.BackgroundRole:
            prev = self.model.header(self.axis, col - 1, row) if col else None
            cur = self.model.header(self.axis, col, row)
            return self._palette.midlight() if prev != cur else None
        if role != Qt.DisplayRole:
            return None
        if self.axis == 0 and self._shape[0] <= 1:
            return None

        header = self.model.header(self.axis, col, row)

        # Don't perform any conversion on strings
        # because it leads to differences between
        # the data present in the dataframe and
        # what is shown by Spyder
        if not is_type_text_string(header):
            header = to_text_string(header)

        return header
Ejemplo n.º 3
0
    def headerData(self, section, orientation, role):
        """Get the information to put in the header."""
        if role == Qt.TextAlignmentRole:
            if orientation == Qt.Horizontal:
                return Qt.AlignCenter | Qt.AlignBottom
            else:
                return Qt.AlignRight | Qt.AlignVCenter
        if role != Qt.DisplayRole and role != Qt.ToolTipRole:
            return None
        if self.axis == 1 and self._shape[1] <= 1:
            return None
        orient_axis = 0 if orientation == Qt.Horizontal else 1
        if self.model.header_shape[orient_axis] > 1:
            header = section
        else:
            header = self.model.header(self.axis, section)

            # Don't perform any conversion on strings
            # because it leads to differences between
            # the data present in the dataframe and
            # what is shown by Spyder
            if not is_type_text_string(header):
                header = to_text_string(header)

        return header
Ejemplo n.º 4
0
 def data(self, index, role=Qt.DisplayRole):
     """Cell content"""
     if not index.isValid():
         return to_qvariant()
     if role == Qt.DisplayRole or role == Qt.EditRole:
         column = index.column()
         row = index.row()
         value = self.get_value(row, column)
         if value is None:
             return ''
         elif np.isnan(value):
             return ''
         elif isinstance(value, float):
             try:
                 return to_qvariant(self._format % value)
             except (ValueError, TypeError):
                 # may happen if format = '%d' and value = NaN;
                 # see issue 4139
                 return to_qvariant(DEFAULT_FORMAT % value)
         elif is_type_text_string(value):
             # Don't perform any conversion on strings
             # because it leads to differences between
             # the data present in the dataframe and
             # what is shown by Spyder
             return value
         else:
             return to_qvariant(to_text_string(value))
     # elif role == Qt.BackgroundColorRole:
     #     return to_qvariant(self.get_bgcolor(index))
     elif role == Qt.FontRole:
         return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA))
     return to_qvariant()
Ejemplo n.º 5
0
 def data(self, index, role=Qt.DisplayRole):
     """Cell content"""
     if not index.isValid():
         return to_qvariant()
     if role == Qt.DisplayRole or role == Qt.EditRole:
         column = index.column()
         row = index.row()
         if column == 0:
             df_idx = self.df_index[row]
             if is_type_text_string(df_idx):
                 # Don't perform any conversion on strings
                 # because it leads to differences between
                 # the data present in the dataframe and
                 # what is shown by Spyder
                 return df_idx
             else:
                 return to_qvariant(to_text_string(df_idx))
         else:
             value = self.get_value(row, column - 1)
             if isinstance(value, float):
                 try:
                     return to_qvariant(self._format % value)
                 except (ValueError, TypeError):
                     # may happen if format = '%d' and value = NaN;
                     # see issue 4139
                     return to_qvariant(DEFAULT_FORMAT % value)
             elif is_type_text_string(value):
                 # Don't perform any conversion on strings
                 # because it leads to differences between
                 # the data present in the dataframe and
                 # what is shown by Spyder
                 return value
             else:
                 try:
                     return to_qvariant(to_text_string(value))
                 except Exception:
                     self.display_error_idxs.append(index)
                     return u'Display Error!'
     elif role == Qt.BackgroundColorRole:
         return to_qvariant(self.get_bgcolor(index))
     elif role == Qt.FontRole:
         return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA))
     elif role == Qt.ToolTipRole:
         if index in self.display_error_idxs:
             return _("It is not possible to display this value because\n"
                      "an error ocurred while trying to do it")
     return to_qvariant()
Ejemplo n.º 6
0
def value_to_display(value, minmax=False, level=0):
    """Convert value for display purpose"""
    # To save current Numpy threshold
    np_threshold = FakeObject

    try:
        numeric_numpy_types = (int64, int32, float64, float32, complex128,
                               complex64)
        if ndarray is not FakeObject:
            # Save threshold
            np_threshold = get_printoptions().get('threshold')
            # Set max number of elements to show for Numpy arrays
            # in our display
            set_printoptions(threshold=10)
        if isinstance(value, recarray):
            if level == 0:
                fields = value.names
                display = 'Field names: ' + ', '.join(fields)
            else:
                display = 'Recarray'
        elif isinstance(value, MaskedArray):
            display = 'Masked array'
        elif isinstance(value, ndarray):
            if level == 0:
                if minmax:
                    try:
                        display = 'Min: %r\nMax: %r' % (value.min(),
                                                        value.max())
                    except (TypeError, ValueError):
                        if value.dtype.type in numeric_numpy_types:
                            display = repr(value)
                        else:
                            display = default_display(value)
                elif value.dtype.type in numeric_numpy_types:
                    display = repr(value)
                else:
                    display = default_display(value)
            else:
                display = 'Numpy array'
        elif any([type(value) == t for t in [list, tuple, dict]]):
            display = collections_display(value, level + 1)
        elif isinstance(value, Image):
            if level == 0:
                display = '%s  Mode: %s' % (address(value), value.mode)
            else:
                display = 'Image'
        elif isinstance(value, DataFrame):
            if level == 0:
                cols = value.columns
                if PY2 and len(cols) > 0:
                    # Get rid of possible BOM utf-8 data present at the
                    # beginning of a file, which gets attached to the first
                    # column header when headers are present in the first
                    # row.
                    # Fixes Issue 2514
                    try:
                        ini_col = to_text_string(cols[0], encoding='utf-8-sig')
                    except:
                        ini_col = to_text_string(cols[0])
                    cols = [ini_col] + [to_text_string(c) for c in cols[1:]]
                else:
                    cols = [to_text_string(c) for c in cols]
                display = 'Column names: ' + ', '.join(list(cols))
            else:
                display = 'Dataframe'
        elif isinstance(value, NavigableString):
            # Fixes Issue 2448
            display = to_text_string(value)
            if level > 0:
                display = u"'" + display + u"'"
        elif isinstance(value, DatetimeIndex):
            if level == 0:
                display = value.summary()
            else:
                display = 'DatetimeIndex'
        elif is_binary_string(value):
            # We don't apply this to classes that extend string types
            # See issue 5636
            if is_type_text_string(value):
                try:
                    display = to_text_string(value, 'utf8')
                    if level > 0:
                        display = u"'" + display + u"'"
                except:
                    display = value
                    if level > 0:
                        display = b"'" + display + b"'"
            else:
                display = default_display(value)
        elif is_text_string(value):
            # We don't apply this to classes that extend string types
            # See issue 5636
            if is_type_text_string(value):
                display = value
                if level > 0:
                    display = u"'" + display + u"'"
            else:
                display = default_display(value)
        elif (isinstance(value, datetime.date)
              or isinstance(value, datetime.timedelta)):
            display = str(value)
        elif (isinstance(value, NUMERIC_TYPES) or isinstance(value, bool)
              or isinstance(value, numeric_numpy_types)):
            display = repr(value)
        else:
            if level == 0:
                display = default_display(value)
            else:
                display = default_display(value, with_module=False)
    except:
        display = default_display(value)

    # Truncate display at 70 chars to avoid freezing Spyder
    # because of large displays
    if len(display) > 70:
        display = display[:70].rstrip() + ' ...'

    # Restore Numpy threshold
    if np_threshold is not FakeObject:
        set_printoptions(threshold=np_threshold)

    return display
Ejemplo n.º 7
0
def value_to_display(value, minmax=False, level=0):
    """Convert value for display purpose"""
    # To save current Numpy threshold
    np_threshold = FakeObject

    try:
        numeric_numpy_types = (int64, int32, int16, int8,
                               uint64, uint32, uint16, uint8,
                               float64, float32, float16,
                               complex128, complex64, bool_)
        if ndarray is not FakeObject:
            # Save threshold
            np_threshold = get_printoptions().get('threshold')
            # Set max number of elements to show for Numpy arrays
            # in our display
            set_printoptions(threshold=10)
        if isinstance(value, recarray):
            if level == 0:
                fields = value.names
                display = 'Field names: ' + ', '.join(fields)
            else:
                display = 'Recarray'
        elif isinstance(value, MaskedArray):
            display = 'Masked array'
        elif isinstance(value, ndarray):
            if level == 0:
                if minmax:
                    try:
                        display = 'Min: %r\nMax: %r' % (value.min(), value.max())
                    except (TypeError, ValueError):
                        if value.dtype.type in numeric_numpy_types:
                            display = str(value)
                        else:
                            display = default_display(value)
                elif value.dtype.type in numeric_numpy_types:
                    display = str(value)
                else:
                    display = default_display(value)
            else:
                display = 'Numpy array'
        elif any([type(value) == t for t in [list, set, tuple, dict]]):
            display = collections_display(value, level+1)
        elif isinstance(value, Image):
            if level == 0:
                display = '%s  Mode: %s' % (address(value), value.mode)
            else:
                display = 'Image'
        elif isinstance(value, DataFrame):
            if level == 0:
                cols = value.columns
                if PY2 and len(cols) > 0:
                    # Get rid of possible BOM utf-8 data present at the
                    # beginning of a file, which gets attached to the first
                    # column header when headers are present in the first
                    # row.
                    # Fixes Issue 2514
                    try:
                        ini_col = to_text_string(cols[0], encoding='utf-8-sig')
                    except:
                        ini_col = to_text_string(cols[0])
                    cols = [ini_col] + [to_text_string(c) for c in cols[1:]]
                else:
                    cols = [to_text_string(c) for c in cols]
                display = 'Column names: ' + ', '.join(list(cols))
            else:
                display = 'Dataframe'
        elif isinstance(value, NavigableString):
            # Fixes Issue 2448
            display = to_text_string(value)
            if level > 0:
                display = u"'" + display + u"'"
        elif isinstance(value, Index):
            if level == 0:
                display = value.summary()
            else:
                display = 'Index'
        elif is_binary_string(value):
            # We don't apply this to classes that extend string types
            # See issue 5636
            if is_type_text_string(value):
                try:
                    display = to_text_string(value, 'utf8')
                    if level > 0:
                        display = u"'" + display + u"'"
                except:
                    display = value
                    if level > 0:
                        display = b"'" + display + b"'"
            else:
                display = default_display(value)
        elif is_text_string(value):
            # We don't apply this to classes that extend string types
            # See issue 5636
            if is_type_text_string(value):
                display = value
                if level > 0:
                    display = u"'" + display + u"'"
            else:
                display = default_display(value)
        elif (isinstance(value, datetime.date) or
              isinstance(value, datetime.timedelta)):
            display = str(value)
        elif (isinstance(value, NUMERIC_TYPES) or
              isinstance(value, bool) or
              isinstance(value, numeric_numpy_types)):
            display = repr(value)
        else:
            if level == 0:
                display = default_display(value)
            else:
                display = default_display(value, with_module=False)
    except:
        display = default_display(value)

    # Truncate display at 70 chars to avoid freezing Spyder
    # because of large displays
    if len(display) > 70:
        display = display[:70].rstrip() + ' ...'

    # Restore Numpy threshold
    if np_threshold is not FakeObject:
        set_printoptions(threshold=np_threshold)

    return display