We wish to format a string as a paragraph with a certain line width. In other words, we wish to insert a newline character at a given line width (in number of characters). This is often useful for display purposes e.g. in notebooks or web apps.
df_2 = df.assign(
col_2 = df['col_1'].str.wrap(width=10)
)
Here is how this works:
str.wrap()
method from the str
accessor set of string manipulation methods of Pandas Series
to wrap the values in the column col_1
into a paragraph where each line has a maximum width of 10 characters.str.wrap()
method acts on one string column and takes one argument width
specifying the target line width.str.wrap()
:df_2
will have the same number of rows as the original data frame df
but with an additional columncol_2
holding the wrapped version of the column col_1
.