klonowsk
Having trouble splitting rows using Explorer.DataFrame
Hi,
I’m having trouble figuring out how to take a dataframe, split one of the text cells based on a function, and create new rows with the results, with all other column data duplicated for each row.
I just can’t figure out how to convert the list of text fragments into something that can be expanded into additional rows.
My (naïve) stab at it looks as follows for now:
require Explorer.DataFrame, as: DF
require Explorer.Series, as: S
defmodule MyDF do
def apply(df, column, new_column, func) do
series = DF.pull(df, column)
list = S.to_list(series)
new_series =
list
|> Enum.map(&func.(&1))
|> S.from_list()
DF.put(df, new_column, new_series)
end
end
df = DF.new(
class: [1, 2, 1, 3],
text: ["AAA, BBB", "CCC, DDD", "EEE", "FFF, GGG, HHH"]
)
df
|> MyDF.apply("text", "new_text", &String.split(&1, ","))
Resulting in:
explorer.DataFrame<
Polars[4 x 3]
class integer [1, 2, 1, 3]
text string [“AAA, BBB”, “CCC, DDD”, “EEE”, “FFF, GGG, HHH”]
new_text list[string] [
[“AAA”, " BBB"],
[“CCC”, " DDD"],
[“EEE”],
[“FFF”, …]
]
But I would like that list of new_text to be spread accross multiple rows.
I’m coming from R+ and tidy/dplyr, where I would do something simple like:
df %>%
dplyr::rowwise() %>%
mutate(new_text = parse_text(text))
Thank you
Marked As Solved
billylanchantin
Whoops! I forgot there was a bug with split which was just fixed last week:
I was on main locally so I didn’t see it. To workaround, you’ll need to do a pipeline like this:
df
|> DF.put("text", S.split(df["text"], ", "))
|> DF.explode("text")
(@bdarla’s approach works too.)
Or you can use main until the next release. Sorry about that!
Also Liked
billylanchantin
Hi @klonowsk,
If I’ve followed what you’re trying to achieve, I think this works:
require Explorer.DataFrame, as: DF
df = DF.new(
class: [1, 2, 1, 3],
text: ["AAA, BBB", "CCC, DDD", "EEE", "FFF, GGG, HHH"]
)
df
|> DF.mutate(text: split(text, ", "))
|> DF.explode("text")
# #Explorer.DataFrame<
# Polars[8 x 2]
# class s64 [1, 1, 2, 2, 1, ...]
# text string ["AAA", "BBB", "CCC", "DDD", "EEE", ...]
# >
bdarla
Indeed, it seems that a previous cell in my Livebook allowed the code to run. Please, try the following:
Mix.install([
{:axon, "~> 0.6"},
{:nx, "~> 0.7"},
{:explorer, "~> 0.8"},
{:kino, "~> 0.12"}
])
require Explorer.DataFrame, as: DF
require Explorer.Series, as: S
text_list = ["AAA, BBB", "CCC, DDD", "EEE", "FFF, GGG, HHH"]
text = S.from_list(text_list)
df = DF.new(
class: [1, 2, 1, 3],
text: text_list
)
split_list = S.split(text, ", ")
df
|> DF.mutate(text: ^split_list)
|> DF.explode(:text)








