Exporting A Pandas DataFrame Into A Python String

Overview:

  • Strings are ubiquitous in computing world. Though there is no separate type called “character” in Python, strings are supported extensively.
  • Strings are texts of arbitrary length. Python strings are immutable.
  • In Python the strings are Unicode.
  • While the pandas DataFrame supports exporting its contents to several formats like CSV, Excel, HDF5 and others, it also supports exporting of a DataFrame object into a string.
  • The method to_string() of the DataFrame class exports the contents of a DataFrame into a Python string.

 

Example:

# Example Python program that exports the contents of a DataFrame into a Python string

import pandas as pds

 

# A dictionary of mappings

mapping = {"S1":(51, 33, 21, 66),

           "S2":(50, 32, 26, 40),

           "S3":(24, 65, 39, 44),

           "S4":(67, 23, 71, 37)}

 

# Construct a pandas DataFrame

df = pds.DataFrame(data=mapping);

 

# Print the pandas DataFrame as a Python string

dataFrameAsString = df.to_string();

print("Contents of the pandas DataFrame as Python string:");

print(dataFrameAsString);

print(type(dataFrameAsString));

 

Output:

Contents of the pandas DataFrame as Python string:

   S1  S2  S3  S4

0  51  50  24  67

1  33  32  65  23

2  21  26  39  71

3  66  40  44  37

<class 'str'>

 


Copyright 2023 © pythontic.com