diff --git a/lib/explorer/data_frame.ex b/lib/explorer/data_frame.ex index 9eee4a461..b3cef91d5 100644 --- a/lib/explorer/data_frame.ex +++ b/lib/explorer/data_frame.ex @@ -3610,6 +3610,10 @@ defmodule Explorer.DataFrame do pairs -> pairs_map = Map.new(pairs) + + if Enum.count(pairs) != map_size(pairs_map), + do: raise(ArgumentError, "duplicate source column for rename") + old_dtypes = df.dtypes for {name, _} <- pairs do diff --git a/native/explorer/src/dataframe.rs b/native/explorer/src/dataframe.rs index 4b32a5c22..0ca0ad0a4 100644 --- a/native/explorer/src/dataframe.rs +++ b/native/explorer/src/dataframe.rs @@ -533,7 +533,7 @@ pub fn df_rename_columns( ) -> Result { let mut df = df.clone(); for (original, new_name) in renames { - df.rename(original, new_name).expect("should rename"); + df.rename(original, new_name)?; } Ok(ExDataFrame::new(df)) diff --git a/test/explorer/data_frame_test.exs b/test/explorer/data_frame_test.exs index 18fa48fb5..d12915843 100644 --- a/test/explorer/data_frame_test.exs +++ b/test/explorer/data_frame_test.exs @@ -2763,6 +2763,38 @@ defmodule Explorer.DataFrameTest do end end + test "with keyword and a column that is duplicated" do + df = DF.new(a: [1, 2, 3], b: ["a", "b", "c"]) + + assert_raise ArgumentError, ~r"duplicate source column for rename", fn -> + DF.rename(df, a: "first", a: "second") + end + end + + test "with mix of column name and index that is duplicated" do + df = DF.new(a: [1, 2, 3], b: ["a", "b", "c"]) + + assert_raise ArgumentError, ~r"duplicate source column for rename", fn -> + DF.rename(df, [{"a", "first"}, {0, "g"}]) + end + end + + test "with string column names that are duplicated" do + df = DF.new(a: [1, 2, 3], b: ["a", "b", "c"]) + + assert_raise ArgumentError, ~r"duplicate source column for rename", fn -> + DF.rename(df, [{"a", "first"}, {"a", "second"}]) + end + end + + test "with string column names and a target that is duplicated" do + df = DF.new(a: [1, 2, 3], b: ["a", "b", "c"]) + + assert_raise RuntimeError, ~r"duplicate column names found", fn -> + DF.rename(df, [{"a", "first"}, {"b", "first"}]) + end + end + test "with a map and a column that doesn't exist" do df = DF.new(a: [1, 2, 3], b: ["a", "b", "c"])