将Polars的`dataframe`序列化为`serde_json::Value`

huangapple go评论53阅读模式
英文:

Serialize Polars `dataframe` to `serde_json::Value`

问题

在Polars中,将DataFrame序列化为JSON字符串非常简单:JsonWriter::new(dest).finish(&df)?

是否可以将其序列化为JSON Value — 一个serde_json::Value,它是记录的Value::Array?显然,我可以将JSON写入内存中的字符串,然后反序列化为serde_json::Value。但我想知道是否有一种直接从DataFrameserde_json::Value的路径。

这将大致等同于pandas的df.to_dict(orient="records")

英文:

In Polars, it is simple enough to serialize a DataFrame to a json string: JsonWriter::new(dest).finish(&df)?.

Is it possible to serialize to a json Value — a serde_json::Value — that is the Value::Array of records? Obviously, I could write the json to an in-memory string, then deserialize it into a serde_json::Value. But I'm wondering if there is a direct path from DataFrame to serde_json::Value.

This would be the rough equivalent of pandas df.to_dict(orient="records").

答案1

得分: 2

你需要添加 serde 功能。

cargo add polars --features serde
use polars::prelude::*;

fn main() {
    let df = df! {
        "a" => [1,2,3,4,5],
    }
    .unwrap();
    let df_json = serde_json::to_value(&df).unwrap();
    println!("df_json {df_json}");
}

请注意,Polars实现了自定义的序列化和反序列化,它可能与提到的pandas等效方法不完全一致。

上述代码的JSON结果:

{
  "columns": [
    {
      "datatype": "Int32",
      "name": "a",
      "values": [1,2,3,4,5]
    }
  ]
}
英文:

You need to add the serde feature.

cargo add polars --features serde
use polars::prelude::*;

fn main() {
    let df = df! {
        "a" => [1,2,3,4,5],
    }
    .unwrap();
    let df_json = serde_json::to_value(&df).unwrap();
    println!("df_json {df_json}");
}

Note, Polars implements a custom de/serialize, and it may not align with the pandas equivalent mentioned.

The JSON result from above:

{
  "columns": [
    {
      "datatype": "Int32",
      "name": "a",
      "values": [1,2,3,4,5]
    }
  ]
}

huangapple
  • 本文由 发表于 2023年3月7日 23:40:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75664099.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定