简体   繁体   English

clojure:根据其他键/值对在映射中计算新的键/值对

[英]clojure: compute a new key/val pair in a map based on other key/val pairs

I have a vector of maps which represents a DataFrame.我有一个表示 DataFrame 的地图向量。 I want to compute a new column (key/val pairs for all maps in the vector).我想计算一个新列(向量中所有映射的键/值对)。 Need some help to do this in the most efficient and idiomatic way.需要一些帮助才能以最有效和惯用的方式做到这一点。

(def dt [{:foo 10 :bar 20 :cat "A"}
         {:foo 15 :bar 10 :cat "B"}
         {:foo 12 :bar 15 :cat "C"}
         {:foo 16 :bar 22 :cat "A"}
         {:foo 13 :bar 11 :cat "B"}
         {:foo 10 :bar 19 :cat "C"}])

What I want to do is define :baz = :foo + :bar.我想要做的是定义 :baz = :foo + :bar。 I can get the computation done with a map operation as follows.我可以通过 map 操作完成计算,如下所示。

(map #(+ (:foo %) (:bar %)) dt)

I would prefer to write a function where the vector is maps is the last argument, so that I can chain operations with the thread-last macro我更愿意编写一个函数,其中向量是 maps 是最后一个参数,以便我可以使用 thread-last 宏链接操作

Something like this:像这样的东西:

(->> dt
     (filter #(= (:foo %) 10))
     (compute-new-column #(...)))

I am beginner in both Clojure and FP, so any additional insights would be appreciated as well.我是 Clojure 和 FP 的初学者,因此任何其他见解也将不胜感激。

If I understand your question correctly you want to add a new key value pair to each map in your collection based on :foo and :bar .如果我正确理解您的问题,您想根据:foo:bar向集合中的每个地图添加一个新的键值对。

(defn compute-new-column [row]
  (assoc row :baz (+ (:foo row) (:bar row))))

Then you can map this function in your thread macro.然后你可以在你的线程宏中映射这个函数。 This is easily done with an anonymous function too as you are doing in your filter.正如您在过滤器中所做的那样,这也可以通过匿名函数轻松完成。

(->> dt
     (filter #(= (:foo %) 10))
     (map compute-new-column))


({:foo 10, :bar 20, :cat "A", :baz 30} {:foo 10, :bar 19, :cat "C", :baz 29})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM