pythonpython-polarspy-shiny

Equivalent to pandas.to_csv() without filename for polars?


Is there an equivalent of casting a Polars DataFrame to a string like for a Pandas DataFrame using pandasdf.to_csv() without an file path ("If None, the result is returned as a string.")?

Similar to this question (How can I cast a Polars DataFrame to string), as a workaround I first cast the Polars DataFrame to a Pandas DataFrame and then use to_csv() without a filename, which results the desiread tab delimited string of the whole Pandas DataFrame:

polarsdf.to_pandas().to_csv(sep='\t', index=False)

What I ultimately want to achieve with that is to download the Polars DataFrame in a Shiny for Python app (similar to this question: How to add "download button" in shiny for pandas dataframe)

This I currently achieve using this code:

def download_something():
    yield polarsdf.to_pandas().to_csv(sep='\t', index=False)

If there is a way of doing this without casting the Polars DataFrame to a string, that would also be a sufficient answer to me.


Solution

  • As jqurious suggested the default behavior of Polars write_csv is to cast a Polars df to a string, if not output file is given:

    polarsdf.write_csv(separator='\t')
    

    And for Shiny for Python this is my solution now:

    def download_something():
        yield polarsdf.write_csv(separator='\t')