M.E.
M.E.

Reputation: 5496

Adding a new column of type Int32 to a julia dataframe using map

I have a string column data with values like 2.323456 and I want to create a new column with an Int32 value like this: 2323456.

I have tried to create a new column using df[!, :newcolumn] and map function, using also parse to parse the string into an Int32.

This works.

However, when I execute an additional transformation with map, it is converted to Int64.

This is my input data:

julia> df2 = DataFrame(low_str=["1.12345", "1.12346", "1.12347"]);

julia> pretty_table(df2, markdown)
| low_str |
|  String |
|---------|
| 1.12345 |
| 1.12346 |
| 1.12347 |

I want to convert that to Int32. So I do:

julia> df2[!, :low] = map(x -> parse( Int32, string( x[1],x[3:7]) ),   df2[:, :low_str]);

julia> pretty_table(df2, markdown)
| low_str |    low |
|  String |  Int32 |
|---------|--------|
| 1.12345 | 112345 |
| 1.12346 | 112346 |
| 1.12347 | 112347 |

So far so good. Now I want to apply a round down so I do:

julia> df2[!, :low] = map( x -> x - mod(x,5), df2[:, :low]);

julia> pretty_table(df2, markdown)
| low_str |    low |
|  String |  Int64 |
|---------|--------|
| 1.12345 | 112345 |
| 1.12346 | 112345 |
| 1.12347 | 112345 |

The data is rounded down correctly but it is now of type Int64 instead of the intended Int32.

How can I preserve the Int32?

Upvotes: 1

Views: 574

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69869

The simplest way to do it (and at the same time in-place, so it is fast) is:

df2.low .-= mod.(df2.low, 5)

If you want to use map! then something like this produces you the desired result:

map!(x -> x - mod(x,5), df2.low, df2.low)

Upvotes: 1

Related Questions