In this short post, you'll see how to pretty print newlines inside the values in Pandas DataFrame. Brief example is included for demonstration purposes.
You can find the two ways below:
(1) Using df.to_html().replace
(2) By df.style.set_properties
Suppose we have a DataFrame like:
name | url | url2 |
---|---|---|
Softhints | https://www.softhints.com | https://www.blog.softhints.com/tag/pandas |
DataScientyst | https://datascientyst.com | https://datascientyst.com/tag/pandas |
Let's create new column which is concatenation of all others with separator a new line:
result:
url2 | all |
---|---|
https://www.blog.softhints.com/tag/pandas | Softhints\nhttps://www.softhints.com\nhttps://www.blog.softhints.com/tag/pandas |
https://datascientyst.com/tag/pandas | DataScientyst\nhttps://datascientyst.com\nhttps://datascientyst.com/tag/pandas |
As you can see default print is showing the string values as a single line - ignoring the newlines.
df.to_html().replace
If you like to print newlines you need to use the following approach:
To print or display new lines inside columns in Pandas DataFrame you can: * convert the output to HTML
- replace all new lines with
<br>
- HTML tag for new line - display the result as HTML
now all newlines symbols are printed or displayed in Jupyter cells correctly:
url2 | all | |
---|---|---|
0 | https://www.blog.softhints.com/tag/pandas | Softhints https://www.softhints.com https://www.blog.softhints.com/tag/pandas |
1 | https://datascientyst.com/tag/pandas | DataScientyst https://datascientyst.com https://datascientyst.com/tag/pandas |
You can define also a method like:
df.style.set_properties
Alternative method is by changing Pandas properties:
white-space
text-align
Let say you would like to have newlines and centered values. Then you can use style.set_properties
with the following values: