Class: Charty::PandasIndex

Inherits:
Index
  • Object
show all
Defined in:
lib/charty/index.rb

Instance Attribute Summary

Attributes inherited from Index

#name, #values

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Index

#[], #initialize

Constructor Details

This class inherits a constructor from Charty::Index

Class Method Details

.try_convert(obj) ⇒ Object



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/charty/index.rb', line 145

def self.try_convert(obj)
  case obj
  when PandasIndex
    obj
  when ->(x) { defined?(Pandas) && x.is_a?(Pandas::Index) }
    PandasIndex.new(obj)
  when RangeIndex, Range
    obj = obj.values if obj.is_a?(RangeIndex)
    stop = if obj.exclude_end?
             obj.end
           else
             obj.end + 1
           end
    PandasIndex.new(Pandas.RangeIndex.new(obj.begin, stop))
  when ->(x) { defined?(Enumerator::ArithmeticSequence) && x.is_a?(Enumerator::ArithmeticSequence) }
    stop = if obj.exclude_end?
             obj.end
           else
             obj.end + 1
           end
    PandasIndex.new(Pandas::RangeIndex.new(obj.begin, stop, obj.step))
  when Index, Array, DaruIndex, ->(x) { defined?(Daru) && x.is_a?(Daru::Index) }
    obj = obj.values if obj.is_a?(Index)
    PandasIndex.new(Pandas::Index.new(obj.to_a))
  else
    nil
  end
end

Instance Method Details

#==(other) ⇒ Object



180
181
182
183
184
185
186
187
188
189
190
# File 'lib/charty/index.rb', line 180

def ==(other)
  case other
  when PandasIndex
    Numpy.all(values == other.values)
  when Index
    return false if length != other.length
    Numpy.all(values == other.values.to_a)
  else
    super
  end
end

#each(&block) ⇒ Object



192
193
194
195
196
197
198
199
200
# File 'lib/charty/index.rb', line 192

def each(&block)
  return enum_for(__method__) unless block_given?

  i, n = 0, length
  while i < n
    yield self[i]
    i += 1
  end
end

#lengthObject



176
177
178
# File 'lib/charty/index.rb', line 176

def length
  size
end

#loc(key) ⇒ Object



202
203
204
205
206
207
208
209
# File 'lib/charty/index.rb', line 202

def loc(key)
  case values
  when Pandas::Index
    values.get_loc(key)
  else
    super
  end
end

#union(other) ⇒ Object



211
212
213
214
215
216
# File 'lib/charty/index.rb', line 211

def union(other)
  other = PandasIndex.try_convert(other)
  # NOTE: Using `sort=False` in pandas.Index#union does not produce pandas.RangeIndex.
  # TODO: Reconsider to use `sort=True` here.
  PandasIndex.new(values.union(other.values, sort: false))
end