Types and Parsing
Parse Formatted Numbers
Convert number strings that contain formatting characters (commas as
thousands separators) to integers. By hand, call str.replace(',', '')
to strip the commas before passing to int. With pandas, chain
Series.str.replace(',', '') and .astype(int) to do the same
column-wide in two steps.
By hand
With pandas
.str.replace(',', '') strips every comma from the string column (dtype
stays object). Chaining .astype(int) then converts the cleaned strings
to int64. The snapshot shows the dtype change from object to int64,
matching cast-numeric-strings.
naive.py
strings = ['1,200', '3,450', '850', '12,000', '675']
result = []
for s in strings:
result.append(int(s.replace(',', '')))
print('RESULT:', result)
library.py
import pandas as pd
from dalib.display import set_display
set_display()
strings = ['1,200', '3,450', '850', '12,000', '675']
df = pd.DataFrame({'x': strings})
s = df['x'].str.replace(',', '').astype(int)
result = s.tolist()
print('index:', s.index.tolist())
print('dtype before:', df['x'].dtype)
print('dtype after:', s.dtype)
print('RESULT:', result)
index: [0, 1, 2, 3, 4]
dtype before: object
dtype after: int64
RESULT: [1200, 3450, 850, 12000, 675]
Implementation notes
.str.replacedefaults toregex=False(literal replacement). Passregex=Trueonly when you intend a regex pattern — e.g. to strip multiple characters at once with a character class.- For currency strings like
'$1,200.50', chain.str.replace('[$,]', '', regex=True)then.astype(float). - Cross-reference:
cast-numeric-strings(this chapter) for converting already-clean digit strings to integers without pre-processing.