Home > database >  Does Polars module not have a method for appending DataFrames to output files?
Does Polars module not have a method for appending DataFrames to output files?

Time:01-29

Sorry for the question but I'm starting out with polars library.

I was reading the documentation for Polars DataFrame and found that any of the .write_* methods have the argument mode. While pandas DataFrame has the .to_csv() method with the mode parameter available, thus allowing to append the DataFrame to a file. None of the Polars DataFrame output methods seems to have that parameter.

  • Am I missing something?
  • How should I Append a Polar DataFrame to a file using polars?
  • Should I instead include csv or pandas modules into my code?

CodePudding user response:

To append to a CSV file for example - you can pass a file object e.g.

import polars as pl

df1 = pl.DataFrame({"a": [1, 2], "b": [3 ,4]})
df2 = pl.DataFrame({"a": [5, 6], "b": [7 ,8]})

with open("out.csv", mode="ab") as f:
   df1.write_csv(f)
   df2.write_csv(f, has_header=False)
>>> from pathlib import Path
>>> print(Path("out.csv").read_text(), end="")
a,b
1,3
2,4
5,7
6,8
  • Related