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

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
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
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
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New

We're in Beta

About us Mission Statement