Skip to content

Commit 315e7a5

Browse files
committed
added better accessor for []=
1 parent d35cf2d commit 315e7a5

File tree

3 files changed

+29
-7
lines changed

3 files changed

+29
-7
lines changed

lib/daru/dataframe.rb

+10-5
Original file line numberDiff line numberDiff line change
@@ -187,13 +187,18 @@ def [](*names)
187187
end
188188

189189
# Insert a new row/vector of the specified name or modify a previous row.
190-
# Instead of using this method directly, use df.row[:a] = [1,2,3] to set/create
191-
# a row ':a' to [1,2,3], or df.vector[:vec] = [1,2,3] for vectors.
190+
# Instead of using this method directly, use df.row[:a] = [1,2,3] to set/create
191+
# a row ':a' to [1,2,3], or df.vector[:vec] = [1,2,3] for vectors.
192192
#
193193
# In case a Daru::Vector is specified after the equality the sign, the indexes
194-
# of the vector will be matched against the row/vector indexes of the DataFrame
195-
# before an insertion is performed. Unmatched indexes will be set to nil.
196-
def []=(name, axis ,vector)
194+
# of the vector will be matched against the row/vector indexes of the DataFrame
195+
# before an insertion is performed. Unmatched indexes will be set to nil.
196+
def []=(*args)
197+
name = args[0]
198+
axis = args[1]
199+
vector = args[-1]
200+
201+
axis = (!axis.is_a?(Symbol) and (axis != :vector or axis != :row)) ? :vector : axis
197202
if axis == :vector
198203
insert_or_modify_vector name, vector
199204
elsif axis == :row

lib/daru/vector.rb

+2-2
Original file line numberDiff line numberDiff line change
@@ -383,8 +383,8 @@ def not_nil?
383383
#
384384
# * +replacement+ - The value which should replace all nils
385385
def replace_nils! replacement
386-
@index.each do |idx|
387-
self[idx] = replacement if self[idx].nil?
386+
nil_positions.each do |idx|
387+
self[idx] = replacement
388388
end
389389

390390
self

spec/dataframe_spec.rb

+17
Original file line numberDiff line numberDiff line change
@@ -488,6 +488,23 @@
488488
end
489489
end
490490

491+
context "#[]=" do
492+
context Daru::Index do
493+
it "assigns directly with the []= operator" do
494+
@data_frame[:a] = [100,200,300,400,500]
495+
expect(@data_frame).to eq(Daru::DataFrame.new({
496+
b: [11,12,13,14,15],
497+
a: [100,200,300,400,500],
498+
c: [11,22,33,44,55]}, order: [:a, :b, :c],
499+
index: [:one, :two, :three, :four, :five]))
500+
end
501+
end
502+
503+
context Daru::MultiIndex do
504+
pending
505+
end
506+
end
507+
491508
context "#[:row]=" do
492509
context Daru::Index do
493510
before :each do

0 commit comments

Comments
 (0)