Class: CADataFrame::ILocAccessor

Inherits:
Object
  • Object
show all
Defined in:
lib/carray-dataframe/iloc_accessor.rb

Instance Method Summary collapse

Constructor Details

#initialize(dataframe) ⇒ ILocAccessor

Returns a new instance of ILocAccessor.



5
6
7
# File 'lib/carray-dataframe/iloc_accessor.rb', line 5

def initialize (dataframe)
  @dataframe = dataframe
end

Instance Method Details

#[](*argv) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/carray-dataframe/iloc_accessor.rb', line 9

def [] (*argv)
  @dataframe.instance_eval {
    index = argv.first
    column_selector = select_columns(argv[1])
    columns = {}
    column_selector.each do |name|
      columns[name] = @column_data[name][index] ### df[...]
    end
    return CADataFrame.new(columns, index: @row_index ? @row_index[index] : nil)
  }
end

#[]=(*argv) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/carray-dataframe/iloc_accessor.rb', line 21

def []= (*argv)
  value = argv.pop
  @dataframe.instance_eval {
    index = argv.first
    column_selector = select_columns(argv[1])
    case value
    when Hash          ### value = {"a"=> [1,2,3], ... }
      value = value.map{|k,v| [k.to_s, v]}.to_h
      column_selector.each do |name|
        @column_data[name][index] = value[name]
      end
    when Array
      case value.first
      when Hash        ### value = [{"a"=>1,"b"=>11}, {"a"=>2,""=>12} ...]
        table = {}
        column_selector.each do |name|
          table[name] = []
        end
        value.each do |hash|
          hash = hash.map{|k,v| [k.to_s, v]}.to_h
          column_selector.each do |name|
            table[name] << hash[name]
          end
        end
        column_selector.each do |name|
          @column_data[name][index] = table[name]
        end
      else             ### value = [[1,11],[2,12],...]
        value = value.transpose
        column_selector.each_with_index do |name, k|
          @column_data[name][index] = value[k]
        end
      end
    else               ### value = any value
      column_selector.each_with_index do |name, k|
        @column_data[name][index] = value
      end
    end
  }
end