Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating data in DataFrame: how to calculate the square of a column

I would like to calculate the square of a column A 1,2,3,4, process it with other calculation store it in column C

using CSV, DataFrames
df = DataFrame(A = 1:4, B = ["M", "F", "F", "M"])
df.C = ((((df.A./2).^2).*3.14)./1000)

Is there an easier way to write it?

like image 596
ecjb Avatar asked Jul 09 '20 14:07

ecjb


1 Answers

I am not sure how much shorter you would want the formula to be, but you can write:

df.C = @. (df.A / 2) ^ 2 * 3.14 / 1000

to avoid having to write . everywhere.

Or you can use transform!, but it is not shorter (its benefit is that you can uset it in a processing pipeline, e.g. using Pipe.jl):

transform!(df, :A => ByRow(a -> (a / 2) ^ 2 * 3.14 / 1000) => :C)
like image 176
Bogumił Kamiński Avatar answered Jan 02 '23 23:01

Bogumił Kamiński