![]() |
VOOZH | about |
Pandas is a powerful Python library for data manipulation, with DataFrame as its key two-dimensional, labeled data structure. It allows easy formatting and readable display of data. DataFrame.to_string() function in Pandas is specifically designed to render a DataFrame into a console-friendly tabular format as a string output. Example:
Weight Name Age 0 45 Sam 14 1 88 Andrea 25 2 56 Alex 55 3 15 Robin 8 4 71 Kia 21
Explanation: This code creates a DataFrame from a dictionary with three columns (Weight, Name, Age), structures it into a tabular format using pd.DataFrame() and converts it into a fully visible string representation with df.to_string().
DataFrame.to_string(buf=None, columns=None, col_space=None, header=True, index=True, na_rep='NaN', formatters=None, float_format=None, sparsify=None, index_names=True, justify=None, max_rows=None, max_cols=None, show_dimensions=False, decimal='.', line_width=None)
Parameters:
Returns: The function returns a str containing the formatted DataFrame.
Weight Name Age 45 Sam 14 88 Andrea 25 56 Alex 55 15 Robin 8 71 Kia 21
Explanation: to_string(index=False) method removes the default index labels from the output. Instead of displaying row indices (0, 1, 2, etc.), only the column values are printed in a structured format.
A B C D 0 12.0 7.0 20 14.0 1 4.0 2.0 16 3.0 2 5.0 54.0 11 Missing 3 Missing 3.0 3 2.0 4 1.0 Missing 8 6.0
Explanation: When dealing with missing values (NaN), the na_rep='Missing' argument replaces them with the string "Missing". This ensures better readability and prevents confusion with empty spaces or default NaN values.
Value 0 3.14 1 2.72 2 1.62
Explanation: float_format="{:.2f}".format argument rounds floating-point numbers to two decimal places. It ensures numerical data is formatted cleanly, making it easier to interpret without excessive decimal precision.
Weight ... Age 0 45 ... 14 .. ... ... .. 4 71 ... 21
Explanation: max_rows=3 and max_cols=2 arguments limit the number of rows and columns displayed. If the DataFrame exceeds these limits, Pandas inserts ellipses (...) to indicate truncated data.