GordianGo

GordianGo

Howto set the decimal separator when reading with CSV.decode() or Explorer.DataFrame.load_csv()

Hi,
my csv file that i want to read is from DE-region (Germany). There they use comma as decimal separator for floating point numbers. eg 4,58

Unfortunately I cannot identitfy a parameter in the documentation to specify another decimal separator for these functions:

Because of the decimal separator (in my case “,” instead of “.”) it will throw an error if defining the datatype of the columns in the csv file on reading with CSV.decode (…) or Dataframe.load_csv(…)

Example:
df = DF.load_csv!(content, dtypes: [{“myFloatCol”,:f64}])

→ throws the expected error:
RuntimeError{message: "Polars Error: could not parse \"4,58\" as dtype f64 at column ‘myFloatCol’ (column number 4)

What would be a good practice?"

Thanks for your advice
Gordian

Most Liked

al2o3cr

al2o3cr

You could use field_transform to accomplish most of this, by passing String.replace:

String.replace("-123,45", ~r/^(-?)(\d+),(\d+)$/, "\\1\\2.\\3")

(adjust further if you’re expecting scientific notation too)

dimitarvp

dimitarvp

Can you give an example of a few CSV rows? F.ex. do they look like this?

ABC,123,4,58,DEF

And you expect ["ABC", "123", "4.58", "DEF"] but get ["ABC", "123", "4", "58", "DEF"] instead? Is that the problem? Sounds like you basically have an invalid CSV when we get down to it. Don’t think that even field_transform can help you in this case.

You can use the xsv tool to extract the “defective” columns and reformat the numbers to be dot-separated and then you can re-merge (or replace) the data back – I’ve done something very similar in the past, successfully. From then on you can just use any normal CSV parser.

billylanchantin

billylanchantin

I did some digging. Polars actually has a relevant option to polars.read_csv() called decimal_comma that Explorer does not expose:

decimal_comma
Parse floats using a comma as the decimal separator instead of a period.

We could certainly expose it. However even if it were exposed, you can’t use it for your example because your CSV also has a , as the separator:

polars.exceptions.InvalidOperationError: 'decimal_comma' argument cannot be combined with ',' separator

So it seems Polars, and therefore Explorer, requires a certain subset of CSV to parse directly into a float like you’re hoping to do.

However @dimitarvp is right to call out mutate. General rule with Explorer: it’s usually fastest to get Rust to do the work if you can. So I suggest the following:

require Explorer.DataFrame, as: DataFrame

csv_path
|> DataFrame.from_csv!()
|> DataFrame.mutate(for col <- across() do
  {col.name, col |> replace(",", ".") |> cast(:f64)}
end)

With this approach, you load what happens to be in the CSV into Rust, then let Rust do the string manipulation.

Where Next?

Popular in Questions Top

pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New

Other popular topics Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

We're in Beta

About us Mission Statement