@@ -72,6 +72,43 @@ def initialize(data = nil, schema: nil, schema_overrides: nil, strict: true, ori
7272 end
7373 end
7474
75+ # Read a serialized DataFrame from a file.
76+ #
77+ # @param source [Object]
78+ # Path to a file or a file-like object (by file-like object, we refer to
79+ # objects that have a `read` method, such as a file handler or `StringIO`).
80+ #
81+ # @return [DataFrame]
82+ #
83+ # @note
84+ # Serialization is not stable across Polars versions: a LazyFrame serialized
85+ # in one Polars version may not be deserializable in another Polars version.
86+ #
87+ # @example
88+ # df = Polars::DataFrame.new({"a" => [1, 2, 3], "b" => [4.0, 5.0, 6.0]})
89+ # bytes = df.serialize
90+ # Polars::DataFrame.deserialize(StringIO.new(bytes))
91+ # # =>
92+ # # shape: (3, 2)
93+ # # ┌─────┬─────┐
94+ # # │ a ┆ b │
95+ # # │ --- ┆ --- │
96+ # # │ i64 ┆ f64 │
97+ # # ╞═════╪═════╡
98+ # # │ 1 ┆ 4.0 │
99+ # # │ 2 ┆ 5.0 │
100+ # # │ 3 ┆ 6.0 │
101+ # # └─────┴─────┘
102+ def self . deserialize ( source )
103+ if Utils . pathlike? ( source )
104+ source = Utils . normalize_filepath ( source )
105+ end
106+
107+ deserializer = RbDataFrame . method ( :deserialize_binary )
108+
109+ _from_rbdf ( deserializer . ( source ) )
110+ end
111+
75112 # @private
76113 def self . _from_rbdf ( rb_df )
77114 df = DataFrame . allocate
@@ -627,6 +664,44 @@ def to_series(index = 0)
627664 Utils . wrap_s ( _df . select_at_idx ( index ) )
628665 end
629666
667+ # Serialize this DataFrame to a file or string.
668+ #
669+ # @param file [Object]
670+ # File path or writable file-like object to which the result will be written.
671+ # If set to `None` (default), the output is returned as a string instead.
672+ #
673+ # @return [Object]
674+ #
675+ # @note
676+ # Serialization is not stable across Polars versions: a LazyFrame serialized
677+ # in one Polars version may not be deserializable in another Polars version.
678+ #
679+ # @example
680+ # df = Polars::DataFrame.new(
681+ # {
682+ # "foo" => [1, 2, 3],
683+ # "bar" => [6, 7, 8]
684+ # }
685+ # )
686+ # bytes = df.serialize
687+ # Polars::DataFrame.deserialize(StringIO.new(bytes))
688+ # # =>
689+ # # shape: (3, 2)
690+ # # ┌─────┬─────┐
691+ # # │ foo ┆ bar │
692+ # # │ --- ┆ --- │
693+ # # │ i64 ┆ i64 │
694+ # # ╞═════╪═════╡
695+ # # │ 1 ┆ 6 │
696+ # # │ 2 ┆ 7 │
697+ # # │ 3 ┆ 8 │
698+ # # └─────┴─────┘
699+ def serialize ( file = nil )
700+ serializer = _df . method ( :serialize_binary )
701+
702+ Utils . serialize_polars_object ( serializer , file )
703+ end
704+
630705 # Serialize to JSON representation.
631706 #
632707 # @param file [String]
0 commit comments