Search code examples
pandasdataframefunctional-programmingapplyhy

How to use the pandas apply method in hy


I'd like to create a new column in pandas using the .apply method where I can pass a custom function

df["newcol"] = df["oldcol"].apply(lambda x: x + 1)
or
df["newcol"] = df.apply(lambda row: row["oldcol"]+1)

How to achieve this in hy ?

so far I am able to do

(setv (get df "newcol") (. (get d "oldcol") apply)

which just sets newcol to oldcol, but couldn't figure out how to define a function to apply.


Solution

  • I recommend reading through the tutorial, which covers topics such as calling methods and defining anonymous functions. A literal Hy translation of

    df["newcol"] = df.apply(lambda row: row["oldcol"]+1)
    

    is

    (setv (get df "newcol") (.apply df (fn [row] (+ (get row "oldcol") 1))))