Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Julia DataFrame: shift a column by more rows

I am looking for a way how to shift DataFrame column by more rows.

Shifting by one row works fine:

df = DataFrame(A=[1,2,3,4], B=[9,8,7,6])

julia> transform(df, "A" => ShiftedArrays.lag => :A1)
4Γ—3 DataFrame
 Row β”‚ A      B      A1
     β”‚ Int64  Int64  Int64?
─────┼───────────────────────
   1 β”‚     1      9  missing
   2 β”‚     2      8        1
   3 β”‚     3      7        2
   4 β”‚     4      6        3

But I am not able to find out how to transform the entire column with a function with more arguments, something like this (neither works):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

transform(df, "A" => x -> ShiftedArrays.lag(x, 2) => :A1)

or

transform(df, ["A", 2] => f => :A1)

I hope there is a more suitable solution than using of for loop πŸ™‚

>Solution :

You need additional parentheses around the lambda function:

transform(df, "A" => (x -> ShiftedArrays.lag(x, 2)) => :A1)

Result:
 Row β”‚ A      B      A1      
     β”‚ Int64  Int64  Int64?  
─────┼───────────────────────
   1 β”‚     1      9  missing 
   2 β”‚     2      8  missing 
   3 β”‚     3      7        1
   4 β”‚     4      6        2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading