We wish to format the string representation of numbers in a certain way typically for display purposes.
We will cover two common scenarios which are:
This section is concerned with the string representation of numbers. See Numeric for coverage of the display settings of numbers.
df_2 = df.assign(
col_2 = df['col_1'].map('{:.0f}'.format)
)
Here is how this works:
1000
as 1e+03
and is often triggered automatically when displaying large numbers.format()
applied to the string (format specifier) '{:.0f}'
. See Decimal Places below for a description of this format specifier.map()
to iterate over each value of the column col_1
and apply the function format()
as described above. Equivalently, we can use apply()
with axis=1
.We wish to add comma separators between each three digits in the string representation of large numbers.
In this example, we wish to create a new column col_2
that is a string representation of the numeric column col_1
with commas added between every three digits.
df_2 = df.assign(
col_2 = df['col_1'].map('{:,d}'.format)
)
Here is how this works:
1000000
is displayed as 1,000,000
.format()
applied to the string (format specifier) '{:,d}'
.':'
inside the placeholder is used to specify the formatting options for the value that will be passed to the placeholder.','
inside the placeholder is used to add a comma as a thousands separator.'d'
inside the placeholder is used to format the value as a decimal number.map()
to iterate over each value of the column col_1
and apply the function format()
as described above. Equivalently, we can use apply()
with axis=1
.We wish to specify the number of decimal places (after the decimal point) to display in a string representation of a floating point number.
df_2 = df.assign(
col_2 = df['col_1'].round(2).map('{:.2f}'.format)
)
Here is how this works:
df['col_1'].round(2)
, we use the method round()
to round each number in the column col_1
to two decimal places.format()
applied to the string (format specifier) '{:,d}'
.':'
inside the placeholder is used to specify the formatting options for the value that will be passed to the placeholder.'.'
inside the placeholder is used to specify the number of decimal places.'2'
after the dot is the desired number of decimal places.'f'
inside the placeholder is used to format the value as a floating-point number.map()
to iterate over each value of the column col_1
and apply the function format()
as described above. Equivalently, we can use apply()
with axis=1
.Extension: String to Numeric to String
df_2 = df.assign(
col_2 = df['col_1']
.astype(float)
.round(2)
.map('{:.2f}'.format)
)
Here is how this works:
col_1
is a string, we will first need to convert it to a numeric data type so we may round it.astype(float)
to convert a string to a numeric data type. See Numeric.