Documenting the answer that worked for me based on the comment by @piRSquared.

I needed to convert to a string first, then an integer.

>>> df['purchase'].astype(str).astype(int)
Answer from cyril on Stack Overflow
🌐
Quora
quora.com › How-do-you-convert-an-integer-to-an-object-in-Python
How to convert an integer to an object in Python - Quora
Answer: For converting an integer to an object in python what you can simply do is, # Use the function float() to turn an object into an integer object = '123.456' / it is in String because we used ‘ ’. number = int(object) number # Output: # 123.456 You can also refer to this for changing...
Discussions

How do you change object to int in dataset
So you want "W19S01" to become the integer 1901? Then you're going to need to first remove the letters and then cast it as an integer using int() More on reddit.com
🌐 r/learnpython
11
3
April 20, 2022
Coverting data type of a df column from obj to int
Hi, I have an assignment due next week which I am very stuck on and I am hoping for guidance. I am stuck on preprocessing data so if I can’t clear this up I will not progress far with this assignment. I have a column in my data frame app_df[‘Size’] which is an obj data type. More on discuss.python.org
🌐 discuss.python.org
9
0
May 3, 2022
Top answer
1 of 2
2

Reading through the documents for sklearn. This package has thorough documentation. In particular the Preprocessing section on encoding categorical features:

In regards to keeping categorical features represented in an array of integers, ie [1,2,3,4,5], we have this:

Such integer representation can not be used directly with scikit-learn estimators, as these expect continuous input, and would interpret the categories as being ordered, which is often not desired (i.e. the set of browsers was ordered arbitrarily). One possibility to convert categorical features to features that can be used with scikit-learn estimators is to use a one-of-K or one-hot encoding, which is implemented in OneHotEncoder. This estimator transforms each categorical feature with m possible values into m binary features, with only one active.

So what you can to do is convert your array into 5 new columns (this case, since you have 5 possible values) using one-hot encoding.

Here is some working code. The input is a column of categorical parameters [1,2,3,4,5], the ouput is a matrix, 5 columns, 1 for each of the 5 possible choices:

from sklearn.preprocessing import OneHotEncoder

enc = OneHotEncoder()
enc.fit([[1],[2],[3],[4],[5]])  
OneHotEncoder(categorical_features='all', dtype='numpy.float64', handle_unknown='error', n_values='auto', sparse=True)
print enc.transform([[1],[2],[3],[4],[5]]).toarray()

Output:

[[ 1.  0.  0.  0.  0.]
 [ 0.  1.  0.  0.  0.]
 [ 0.  0.  1.  0.  0.]
 [ 0.  0.  0.  1.  0.]
 [ 0.  0.  0.  0.  1.]]

Say your categorical parameters were in this order: [1,3,2,5,4,3,2,1,3,4,2]. You would get this output:

[[ 1.  0.  0.  0.  0.]
 [ 0.  0.  1.  0.  0.]
 [ 0.  1.  0.  0.  0.]
 [ 0.  0.  0.  0.  1.]
 [ 0.  0.  0.  1.  0.]
 [ 0.  0.  1.  0.  0.]
 [ 0.  1.  0.  0.  0.]
 [ 1.  0.  0.  0.  0.]
 [ 0.  0.  1.  0.  0.]
 [ 0.  0.  0.  1.  0.]
 [ 0.  1.  0.  0.  0.]]

So this 1 column will convert into 5 columns.

2 of 2
0
print(data.dtypes)
data["col_name"]=data["col_name"].astype(str)
print(data.dtypes)
🌐
Reddit
reddit.com › r/learnpython › how do you change object to int in dataset
r/learnpython on Reddit: How do you change object to int in dataset
April 20, 2022 -

In the dataset that I am trying to process with python include Dtypes: object/int64/float64 and I am trying to change all the data to int64. The problem I think is that one of my data column include both numbers and letters (W19S01) so I get the following error when I try to convert the Dtype: ValueError: invalid literal for int() with base 10: 'W19S01'
So far I have tried to change the data type to string using df[cols] = df[cols].to_string().strip() then changing it back to float/int64 and it still shows ValueError: could not convert string to float: 'W19S01'
I havealso tried to replace the letters in data set with empty space using df['Subject Yr Student ID'].str.replace('W', '').str.replace('S', '')
So far no luck and I am fairly new to python

🌐
Programiz
programiz.com › python-programming › type-conversion-and-casting
Python Type Conversion (With Examples)
In Explicit Type Conversion, users convert the data type of an object to required data type. We use the built-in functions like int(), float(), str(), etc to perform explicit type conversion. This type of conversion is also called typecasting because the user casts (changes) the data type of ...
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.convert_dtypes.html
pandas.DataFrame.convert_dtypes — pandas 3.0.6 documentation
Then, if possible, convert to StringDtype, BooleanDtype or an appropriate integer or floating extension type, otherwise leave as object. If the dtype is integer, convert to an appropriate integer extension type. If the dtype is numeric, and consists of all integers, convert to an appropriate integer extension type. Otherwise, convert to an appropriate floating extension type. In the future, as new dtypes are added that support pd.NA, the results of this method will change to support those new dtypes. ... >>> df = pd.DataFrame( ...
🌐
YouTube
youtube.com › machine mantra
How to Convert Data Types in Pandas Data Frame| Python - YouTube
Learn various ways on how to convert data types in Pandas data frame, Convert Object data type to int, float to object. Functions like astype(), infer_object...
Published: December 3, 2020
Views: 3K
🌐
DataCamp
datacamp.com › tutorial › python-data-type-conversion
Python Data Type Conversion: A Guide With Examples | DataCamp
February 16, 2025 - What the program should do here might seem intuitive to you. However, the compiler might not always be sure, so it provides a mechanism with explicit type casting so that you can clearly state what you want. This is how you can convert an integer to a string in Python using the str() function:
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › type-casting-in-python
Type Casting in Python - GeeksforGeeks
Explicit type conversion is when ... Commonly used type casting functions in Python are: Int() function take float or string as an argument and returns int type object....
Published: July 29, 2026
🌐
Linode
linode.com › docs › guides › how-to-convert-datatypes-in-python
How to Convert Data Types in Python | Linode Docs
June 3, 2022 - Mathematical operations cannot be performed on string objects. They must be converted to numbers first. Fortunately, Python’s built-in int() function is very flexible and can convert several data types to integers.
🌐
Statology
statology.org › home › pandas: how to convert object to int
Pandas: How to Convert object to int
July 16, 2022 - The following code shows how to convert multiple columns in a DataFrame from an object to an integer: #convert 'points' and 'assists' columns to integer df[['points', 'assists']] = df[['points', 'assists']].astype(str).astype(int) #view data types for each column df.dtypes player object points int32 assists int32 dtype: object
🌐
Vaia
vaia.com › en-us › explanations › computer-science › computer-programming › change-data-type-in-python
Vaia | The #1 learning app for university & school
February 25, 2026 - Our AI is integrated across our platform, helping you generate learning materials and giving you feedback.
🌐
Sentry
sentry.io › sentry answers › python › change a column type in a dataframe in python pandas
Change a column type in a DataFrame in Python Pandas
import pandas as pd # Create and print DataFrame df = pd.DataFrame({ 'A': ['1', '2', '3'], 'B': ['4.0', '5.1', '6.2'], 'C': ['7', '8', '9'] }) print(df) # Print data types of each column in DataFrame print("\n") print(df.dtypes) # Change column A's values to a numeric type df['A'] = pd.to_numeric(df['A']) # Change column B and C's values to a numeric type df[['B', 'C']] = df[['B', 'C']].apply(pd.to_numeric) print("\nConverted:\n") # Print altered DataFrame print(df) # Print data types of each column in DataFrame print("\n") print(df.dtypes) ... A B C 0 1 4.0 7 1 2 5.1 8 2 3 6.2 9 A object B object C object dtype: object Converted: A B C 0 1 4.0 7 1 2 5.1 8 2 3 6.2 9 A int64 B float64 C int64 dtype: object
🌐
Pandas
pandas.pydata.org › pandas-docs › stable › reference › api › pandas.DataFrame.astype.html
pandas.DataFrame.astype — pandas 3.0.6 documentation
Cast a numpy array to a specified type. ... Changed in version 2.0.0: Using astype to convert from timezone-naive dtype to timezone-aware dtype will raise an exception. Use Series.dt.tz_localize() instead. ... >>> d = {"col1": [1, 2], "col2": [3, 4]} >>> df = pd.DataFrame(data=d) >>> df.dtypes col1 int64 col2 int64 dtype: object
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-convert-data-types-in-python-3
How To Convert Data Types in Python 3 | DigitalOcean
This Python 3 tutorial will guide you through converting data types including numbers, strings, tuples and lists, as well as provide examples to help familia…
🌐
APXML
apxml.com › courses › python-for-beginners › chapter-2-python-basics-variables-data-types-operators › python-type-conversion
Python Type Conversion | Casting Data Types
Python variables can store various data types, but the specific type is crucial when performing operations. For instance, directly adding a number and a string representation of a number, like 42 + "10", will not work mathematically. Python interprets "10" as text, not the numerical value ten. To enable such an operation, you must explicitly instruct Python to treat "10" as a number. This change in a value's data type is known as type conversion or type casting.
🌐
GeeksforGeeks
geeksforgeeks.org › convert-the-data-type-of-pandas-column-to-int
Convert the data type of Pandas column to int - GeeksforGeeks
January 13, 2021 - Once a pandas.DataFrame is created using external data, systematically numeric columns are taken to as data type objects instead of int or float, creating numeric tasks not possible. We will pass any Python, Numpy, or Pandas datatype to vary all columns of a dataframe thereto type, or we will pass a dictionary having column names as keys and datatype as values to vary the type of picked columns.
🌐
Quora
quora.com › How-can-you-convert-an-object-into-another-type-in-Python
How to convert an object into another type in Python - Quora
Answer (1 of 4): To convert an object from one type to another type in Python, we use what is called type casting. Type casting explicitly convert an object from one type to another type. To cast an object from one type to another, the object is wrapped in the type function using the type keywo...
🌐
Python.org
discuss.python.org › python help
Coverting data type of a df column from obj to int - Python Help - Discussions on Python.org
May 3, 2022 - Hi, I have an assignment due next week which I am very stuck on and I am hoping for guidance. I am stuck on preprocessing data so if I can’t clear this up I will not progress far with this assignment. I have a column in my data frame app_df[‘Size’] which is an obj data type.