You have four main options for converting types in pandas:

  1. to_numeric() - provides functionality to safely convert non-numeric types (e.g. strings) to a suitable numeric type. (See also to_datetime() and to_timedelta().)

  2. astype() - convert (almost) any type to (almost) any other type (even if it's not necessarily sensible to do so). Also allows you to convert to categorial types (very useful).

  3. infer_objects() - a utility method to convert object columns holding Python objects to a pandas type if possible.

  4. convert_dtypes() - convert DataFrame columns to the "best possible" dtype that supports pd.NA (pandas' object to indicate a missing value).

Read on for more detailed explanations and usage of each of these methods.


1. to_numeric()

The best way to convert one or more columns of a DataFrame to numeric values is to use pandas.to_numeric().

This function will try to change non-numeric objects (such as strings) into integers or floating-point numbers as appropriate.

Basic usage

The input to to_numeric() is a Series or a single column of a DataFrame.

>>> s = pd.Series(["8", 6, "7.5", 3, "0.9"]) # mixed string and numeric values
>>> s
0      8
1      6
2    7.5
3      3
4    0.9
dtype: object

>>> pd.to_numeric(s) # convert everything to float values
0    8.0
1    6.0
2    7.5
3    3.0
4    0.9
dtype: float64

As you can see, a new Series is returned. Remember to assign this output to a variable or column name to continue using it:

# convert Series
my_series = pd.to_numeric(my_series)

# convert column "a" of a DataFrame
df["a"] = pd.to_numeric(df["a"])

You can also use it to convert multiple columns of a DataFrame via the apply() method:

# convert all columns of DataFrame
df = df.apply(pd.to_numeric) # convert all columns of DataFrame

# convert just columns "a" and "b"
df[["a", "b"]] = df[["a", "b"]].apply(pd.to_numeric)

As long as your values can all be converted, that's probably all you need.

Error handling

But what if some values can't be converted to a numeric type?

to_numeric() also takes an errors keyword argument that allows you to force non-numeric values to be NaN, or simply ignore columns containing these values.

Here's an example using a Series of strings s which has the object dtype:

>>> s = pd.Series(['1', '2', '4.7', 'pandas', '10'])
>>> s
0         1
1         2
2       4.7
3    pandas
4        10
dtype: object

The default behaviour is to raise if it can't convert a value. In this case, it can't cope with the string 'pandas':

>>> pd.to_numeric(s) # or pd.to_numeric(s, errors='raise')
ValueError: Unable to parse string

Rather than fail, we might want 'pandas' to be considered a missing/bad numeric value. We can coerce invalid values to NaN as follows using the errors keyword argument:

>>> pd.to_numeric(s, errors='coerce')
0     1.0
1     2.0
2     4.7
3     NaN
4    10.0
dtype: float64

The third option for errors is just to ignore the operation if an invalid value is encountered:

>>> pd.to_numeric(s, errors='ignore')
# the original Series is returned untouched

This last option is particularly useful for converting your entire DataFrame, but don't know which of our columns can be converted reliably to a numeric type. In that case, just write:

df.apply(pd.to_numeric, errors='ignore')

The function will be applied to each column of the DataFrame. Columns that can be converted to a numeric type will be converted, while columns that cannot (e.g. they contain non-digit strings or dates) will be left alone.

Downcasting

By default, conversion with to_numeric() will give you either an int64 or float64 dtype (or whatever integer width is native to your platform).

That's usually what you want, but what if you wanted to save some memory and use a more compact dtype, like float32, or int8?

to_numeric() gives you the option to downcast to either 'integer', 'signed', 'unsigned', 'float'. Here's an example for a simple series s of integer type:

>>> s = pd.Series([1, 2, -7])
>>> s
0    1
1    2
2   -7
dtype: int64

Downcasting to 'integer' uses the smallest possible integer that can hold the values:

>>> pd.to_numeric(s, downcast='integer')
0    1
1    2
2   -7
dtype: int8

Downcasting to 'float' similarly picks a smaller than normal floating type:

>>> pd.to_numeric(s, downcast='float')
0    1.0
1    2.0
2   -7.0
dtype: float32

2. astype()

The astype() method enables you to be explicit about the dtype you want your DataFrame or Series to have. It's very versatile in that you can try and go from one type to any other.

Basic usage

Just pick a type: you can use a NumPy dtype (e.g. np.int16), some Python types (e.g. bool), or pandas-specific types (like the categorical dtype).

Call the method on the object you want to convert and astype() will try and convert it for you:

# convert all DataFrame columns to the int64 dtype
df = df.astype(int)

# convert column "a" to int64 dtype and "b" to complex type
df = df.astype({"a": int, "b": complex})

# convert Series to float16 type
s = s.astype(np.float16)

# convert Series to Python strings
s = s.astype(str)

# convert Series to categorical type - see docs for more details
s = s.astype('category')

Notice I said "try" - if astype() does not know how to convert a value in the Series or DataFrame, it will raise an error. For example, if you have a NaN or inf value you'll get an error trying to convert it to an integer.

As of pandas 0.20.0, this error can be suppressed by passing errors='ignore'. Your original object will be returned untouched.

Be careful

astype() is powerful, but it will sometimes convert values "incorrectly". For example:

>>> s = pd.Series([1, 2, -7])
>>> s
0    1
1    2
2   -7
dtype: int64

These are small integers, so how about converting to an unsigned 8-bit type to save memory?

>>> s.astype(np.uint8)
0      1
1      2
2    249
dtype: uint8

The conversion worked, but the -7 was wrapped round to become 249 (i.e. 28 - 7)!

Trying to downcast using pd.to_numeric(s, downcast='unsigned') instead could help prevent this error.


3. infer_objects()

Version 0.21.0 of pandas introduced the method infer_objects() for converting columns of a DataFrame that have an object datatype to a more specific type (soft conversions).

For example, here's a DataFrame with two columns of object type. One holds actual integers and the other holds strings representing integers:

>>> df = pd.DataFrame({'a': [7, 1, 5], 'b': ['3','2','1']}, dtype='object')
>>> df.dtypes
a    object
b    object
dtype: object

Using infer_objects(), you can change the type of column 'a' to int64:

>>> df = df.infer_objects()
>>> df.dtypes
a     int64
b    object
dtype: object

Column 'b' has been left alone since its values were strings, not integers. If you wanted to force both columns to an integer type, you could use df.astype(int) instead.


4. convert_dtypes()

Version 1.0 and above includes a method convert_dtypes() to convert Series and DataFrame columns to the best possible dtype that supports the pd.NA missing value.

Here "best possible" means the type most suited to hold the values. For example, this a pandas integer type, if all of the values are integers (or missing values): an object column of Python integer objects are converted to Int64, a column of NumPy int32 values, will become the pandas dtype Int32.

With our object DataFrame df, we get the following result:

>>> df.convert_dtypes().dtypes                                             
a     Int64
b    string
dtype: object

Since column 'a' held integer values, it was converted to the Int64 type (which is capable of holding missing values, unlike int64).

Column 'b' contained string objects, so was changed to pandas' string dtype.

By default, this method will infer the type from object values in each column. We can change this by passing infer_objects=False:

>>> df.convert_dtypes(infer_objects=False).dtypes                          
a    object
b    string
dtype: object

Now column 'a' remained an object column: pandas knows it can be described as an 'integer' column (internally it ran infer_dtype) but didn't infer exactly what dtype of integer it should have so did not convert it. Column 'b' was again converted to 'string' dtype as it was recognised as holding 'string' values.

Answer from Alex Riley on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › convert-a-dataframe-column-to-integer-in-pandas
Convert a Dataframe Column to Integer in Pandas - GeeksforGeeks
March 2, 2026 - It is best when you need to apply a straightforward, element-wise transformation to each value in the column, such as converting string values to integers. ... import pandas as pd # Creating a sample DataFrame data = {'Column1': ['1', '2', '3', '4']} df = pd.DataFrame(data) # Using map() method to convert to integers df['Column1'] = df['Column1'].map(int) # Displaying the DataFrame and dtype print(df) print(df['Column1'].dtype)
Top answer
1 of 16
2639

You have four main options for converting types in pandas:

  1. to_numeric() - provides functionality to safely convert non-numeric types (e.g. strings) to a suitable numeric type. (See also to_datetime() and to_timedelta().)

  2. astype() - convert (almost) any type to (almost) any other type (even if it's not necessarily sensible to do so). Also allows you to convert to categorial types (very useful).

  3. infer_objects() - a utility method to convert object columns holding Python objects to a pandas type if possible.

  4. convert_dtypes() - convert DataFrame columns to the "best possible" dtype that supports pd.NA (pandas' object to indicate a missing value).

Read on for more detailed explanations and usage of each of these methods.


1. to_numeric()

The best way to convert one or more columns of a DataFrame to numeric values is to use pandas.to_numeric().

This function will try to change non-numeric objects (such as strings) into integers or floating-point numbers as appropriate.

Basic usage

The input to to_numeric() is a Series or a single column of a DataFrame.

>>> s = pd.Series(["8", 6, "7.5", 3, "0.9"]) # mixed string and numeric values
>>> s
0      8
1      6
2    7.5
3      3
4    0.9
dtype: object

>>> pd.to_numeric(s) # convert everything to float values
0    8.0
1    6.0
2    7.5
3    3.0
4    0.9
dtype: float64

As you can see, a new Series is returned. Remember to assign this output to a variable or column name to continue using it:

# convert Series
my_series = pd.to_numeric(my_series)

# convert column "a" of a DataFrame
df["a"] = pd.to_numeric(df["a"])

You can also use it to convert multiple columns of a DataFrame via the apply() method:

# convert all columns of DataFrame
df = df.apply(pd.to_numeric) # convert all columns of DataFrame

# convert just columns "a" and "b"
df[["a", "b"]] = df[["a", "b"]].apply(pd.to_numeric)

As long as your values can all be converted, that's probably all you need.

Error handling

But what if some values can't be converted to a numeric type?

to_numeric() also takes an errors keyword argument that allows you to force non-numeric values to be NaN, or simply ignore columns containing these values.

Here's an example using a Series of strings s which has the object dtype:

>>> s = pd.Series(['1', '2', '4.7', 'pandas', '10'])
>>> s
0         1
1         2
2       4.7
3    pandas
4        10
dtype: object

The default behaviour is to raise if it can't convert a value. In this case, it can't cope with the string 'pandas':

>>> pd.to_numeric(s) # or pd.to_numeric(s, errors='raise')
ValueError: Unable to parse string

Rather than fail, we might want 'pandas' to be considered a missing/bad numeric value. We can coerce invalid values to NaN as follows using the errors keyword argument:

>>> pd.to_numeric(s, errors='coerce')
0     1.0
1     2.0
2     4.7
3     NaN
4    10.0
dtype: float64

The third option for errors is just to ignore the operation if an invalid value is encountered:

>>> pd.to_numeric(s, errors='ignore')
# the original Series is returned untouched

This last option is particularly useful for converting your entire DataFrame, but don't know which of our columns can be converted reliably to a numeric type. In that case, just write:

df.apply(pd.to_numeric, errors='ignore')

The function will be applied to each column of the DataFrame. Columns that can be converted to a numeric type will be converted, while columns that cannot (e.g. they contain non-digit strings or dates) will be left alone.

Downcasting

By default, conversion with to_numeric() will give you either an int64 or float64 dtype (or whatever integer width is native to your platform).

That's usually what you want, but what if you wanted to save some memory and use a more compact dtype, like float32, or int8?

to_numeric() gives you the option to downcast to either 'integer', 'signed', 'unsigned', 'float'. Here's an example for a simple series s of integer type:

>>> s = pd.Series([1, 2, -7])
>>> s
0    1
1    2
2   -7
dtype: int64

Downcasting to 'integer' uses the smallest possible integer that can hold the values:

>>> pd.to_numeric(s, downcast='integer')
0    1
1    2
2   -7
dtype: int8

Downcasting to 'float' similarly picks a smaller than normal floating type:

>>> pd.to_numeric(s, downcast='float')
0    1.0
1    2.0
2   -7.0
dtype: float32

2. astype()

The astype() method enables you to be explicit about the dtype you want your DataFrame or Series to have. It's very versatile in that you can try and go from one type to any other.

Basic usage

Just pick a type: you can use a NumPy dtype (e.g. np.int16), some Python types (e.g. bool), or pandas-specific types (like the categorical dtype).

Call the method on the object you want to convert and astype() will try and convert it for you:

# convert all DataFrame columns to the int64 dtype
df = df.astype(int)

# convert column "a" to int64 dtype and "b" to complex type
df = df.astype({"a": int, "b": complex})

# convert Series to float16 type
s = s.astype(np.float16)

# convert Series to Python strings
s = s.astype(str)

# convert Series to categorical type - see docs for more details
s = s.astype('category')

Notice I said "try" - if astype() does not know how to convert a value in the Series or DataFrame, it will raise an error. For example, if you have a NaN or inf value you'll get an error trying to convert it to an integer.

As of pandas 0.20.0, this error can be suppressed by passing errors='ignore'. Your original object will be returned untouched.

Be careful

astype() is powerful, but it will sometimes convert values "incorrectly". For example:

>>> s = pd.Series([1, 2, -7])
>>> s
0    1
1    2
2   -7
dtype: int64

These are small integers, so how about converting to an unsigned 8-bit type to save memory?

>>> s.astype(np.uint8)
0      1
1      2
2    249
dtype: uint8

The conversion worked, but the -7 was wrapped round to become 249 (i.e. 28 - 7)!

Trying to downcast using pd.to_numeric(s, downcast='unsigned') instead could help prevent this error.


3. infer_objects()

Version 0.21.0 of pandas introduced the method infer_objects() for converting columns of a DataFrame that have an object datatype to a more specific type (soft conversions).

For example, here's a DataFrame with two columns of object type. One holds actual integers and the other holds strings representing integers:

>>> df = pd.DataFrame({'a': [7, 1, 5], 'b': ['3','2','1']}, dtype='object')
>>> df.dtypes
a    object
b    object
dtype: object

Using infer_objects(), you can change the type of column 'a' to int64:

>>> df = df.infer_objects()
>>> df.dtypes
a     int64
b    object
dtype: object

Column 'b' has been left alone since its values were strings, not integers. If you wanted to force both columns to an integer type, you could use df.astype(int) instead.


4. convert_dtypes()

Version 1.0 and above includes a method convert_dtypes() to convert Series and DataFrame columns to the best possible dtype that supports the pd.NA missing value.

Here "best possible" means the type most suited to hold the values. For example, this a pandas integer type, if all of the values are integers (or missing values): an object column of Python integer objects are converted to Int64, a column of NumPy int32 values, will become the pandas dtype Int32.

With our object DataFrame df, we get the following result:

>>> df.convert_dtypes().dtypes                                             
a     Int64
b    string
dtype: object

Since column 'a' held integer values, it was converted to the Int64 type (which is capable of holding missing values, unlike int64).

Column 'b' contained string objects, so was changed to pandas' string dtype.

By default, this method will infer the type from object values in each column. We can change this by passing infer_objects=False:

>>> df.convert_dtypes(infer_objects=False).dtypes                          
a    object
b    string
dtype: object

Now column 'a' remained an object column: pandas knows it can be described as an 'integer' column (internally it ran infer_dtype) but didn't infer exactly what dtype of integer it should have so did not convert it. Column 'b' was again converted to 'string' dtype as it was recognised as holding 'string' values.

2 of 16
553

Use this:

a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])
df

Out[16]:
  one  two three
0   a  1.2   4.2
1   b   70  0.03
2   x    5     0

df.dtypes

Out[17]:
one      object
two      object
three    object

df[['two', 'three']] = df[['two', 'three']].astype(float)

df.dtypes

Out[19]:
one       object
two      float64
three    float64
Discussions

How to convert a pandas column from strings to int
>>> df col 0 7 Average 1 6 Low Average 2 8 Good 3 11 Excellent 4 9 Better 5 5 Fair 6 10 Very Good 7 12 Luxury 8 4 Low 9 3 Poor 10 13 Mansion >>> df['col'] = df['col'].str.split(n=1, expand=True)[0].astype(int) >>> df col 0 7 1 6 2 8 3 11 4 9 5 5 6 10 7 12 8 4 9 3 10 13 More on reddit.com
🌐 r/learnpython
4
2
July 22, 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
Pandas dataframe columns won't convert to float
could you try this , dp03_cleaned[columns] = dp03_cleaned[columns].apply(pd.to_numeric, errors='coerce') More on reddit.com
🌐 r/learnpython
9
0
May 14, 2022
Pandas. Convert float to integer only if it is a round number.
I can't promise this is the best answer, but could be worth considering anyway. I would convert the data to strings: >>> stringify = lambda i: f'{i}' if i % 1 else f'{i:.0f}' >>> df.cost = df.cost.apply(stringify, axis=1) Then write to a file. This will ensure the data is written to a file in the format you want it. Proof: >>> cost = [1.5, 1.0, 2.6, 4.0] >>> list(map(stringify, cost)) ['1.5', '1', '2.6', '4'] However, note that if you subsequently open it in a "smart" viewer like Excel that tries to auto-detect data types, there's no guarantee it will remain in that format. More on reddit.com
🌐 r/learnpython
7
1
April 12, 2021
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas convert column to int in dataframe
Pandas Convert Column to Int in DataFrame - Spark By {Examples}
June 26, 2025 - How to convert the Pandas column to int in DataFrame? You can use DataFrame.astype(int) or DataFrame.apply() method to convert a column to int
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.read_csv.html
pandas.read_csv — pandas 3.0.3 documentation
Functions for converting values in specified columns. Keys can either be column labels or column indices. ... Values to consider as True in addition to case-insensitive variants of ‘True’. ... Values to consider as False in addition to case-insensitive variants of ‘False’. ... Skip spaces after delimiter. ... Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.astype.html
pandas.DataFrame.astype — pandas 3.0.3 documentation
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 ... >>> ser = pd.Series([1, 2], dtype="int32") >>> ser 0 1 1 2 dtype: int32 >>> ser.astype("int64") 0 1 1 2 dtype: int64 ... >>> from pandas.api.types import CategoricalDtype >>> cat_dtype = CategoricalDtype(categories=[2, 1], ordered=True) >>> ser.astype(cat_dtype) 0 1 1 2 dtype: category Categories (2, int64): [2 < 1]
Find elsewhere
🌐
IncludeHelp
includehelp.com › python › convert-entire-pandas-dataframe-to-integers.aspx
Python - Convert entire pandas dataframe to integers
# Importing pandas package import pandas as pd # Creating a dictionary d = { 'col1':['1.2','4.4','7.2'], 'col2':['2','5','8'], 'col3':['3.9','6.2','9.1'] } # Creating a dataframe df = pd.DataFrame(d) # Display Dataframe print("DataFrame :\n",df,"\n") # Looping over df.columns for i in df.columns: try: df[[i]] = df[[i]].astype(float).astype(int) except: pass # Display data types of dataframe print("New Data type:\n",df.dtypes)
🌐
Data Science Parichay
datascienceparichay.com › home › blog › pandas – convert category type column to integer
Pandas - Convert Category Type Column to Integer - Data Science Parichay
April 1, 2022 - You can use the Pandas astype() function to change the data type of a column. To convert a category type column to integer type, apply the astype() function on the column and pass 'int' as the argument.
🌐
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 | Sentry
If we want to convert a column to a numeric type, we can use the to_numeric function. Depending on the data in our columns, they will be converted into either integers or floats. import pandas as pd # Create and print DataFrame df = pd.DataFrame({ ...
🌐
Statology
statology.org › home › how to convert pandas dataframe columns to int
How to Convert Pandas DataFrame Columns to int
November 28, 2022 - The following code shows how to convert multiple columns in a DataFrame to an integer: import pandas as pd #create DataFrame df = pd.DataFrame({'player': ['A', 'B', 'C', 'D', 'E'], 'points': ['25', '20', '14', '16', '27'], 'assists': ['5', '7', '7', '8', '11']}) #convert 'points' and 'assists' columns to integer df[['points', 'assists']] = df[['points', 'assists']].astype(int) #view data types for each column df.dtypes player object points int64 assists int64 dtype: object
🌐
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…
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.convert_dtypes.html
pandas.DataFrame.convert_dtypes — pandas 3.0.3 documentation
>>> df.dtypes a int32 b object c object d object e float64 f float64 dtype: object · Convert the DataFrame to use best possible dtypes.
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas convert integer to string in dataframe
Pandas Convert Integer to String in DataFrame - Spark By {Examples}
December 5, 2024 - To convert an integer column to a string in a pandas DataFrame, you can use the astype(str) method. Additionally, other Pandas functions like apply(),
🌐
GoLinuxCloud
golinuxcloud.com › home › databases › 7 ways to convert pandas dataframe column to int
7 ways to convert pandas DataFrame column to int | GoLinuxCloud
January 24, 2022 - Here we are going to convert the float type column in DataFrame to integer type using astype() method. we just need to pass int keyword inside this method through dictionary. ... # import the module import pandas # consider the food data ...
🌐
LinkedIn
linkedin.com › pulse › change-data-type-columns-pandas-mohit-sharma
Change the data type of columns in Pandas
February 8, 2021 - The best way to convert one or more columns of a DataFrame to numeric values is to use pandas.to_numeric(). This function will try to change non-numeric objects (such as strings) into integers or floating-point numbers as appropriate.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.groupby.html
pandas.DataFrame.groupby — pandas 3.0.3 documentation
Group DataFrame using a mapper or by a Series of columns. A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups.
🌐
Medium
medium.com › @amit25173 › pandas-float-to-int-a-practical-guide-a288ab2fe3d9
Pandas Float to Int: A Practical Guide | by Amit Yadav | Medium
March 6, 2025 - When working with Pandas DataFrames, ... to be converted into integers. Maybe you’re cleaning data for machine learning, or perhaps you just don’t need those pesky decimal points. Whatever the case, Pandas gives you multiple ways to make this conversion happen. Let’s explore them step by step. Using .astype(int) – The Simple But Tricky Approach · This is the most straightforward method, but there’s a catch — you can’t use it if your column contains NaN ...
🌐
Skytowner
skytowner.com › explore › converting_a_pandas_column_with_missing_values_to_integer_type
Converting a Pandas column with missing values to integer type
import pandas as pd · import numpy as np · df = pd.DataFrame({'A':[3,4,np.nan]}) df · A · 0 3.0 · 1 4.0 · 2 NaN · To convert column A to integer type: df['A'].astype('Int64') 0 3 · 1 4 · 2 <NA> Name: A, dtype: Int64 · WARNING · astype('int') does not work when there is are missing values - only astype('Int64') works.
🌐
PyTorch
docs.pytorch.org › intro › learn the basics › datasets & dataloaders
Datasets & DataLoaders — PyTorch Tutorials 2.12.0+cu130 documentation
July 20, 2022 - import os import pandas as pd from torchvision.io import decode_image class CustomImageDataset(Dataset): def __init__(self, annotations_file, img_dir, transform=None, target_transform=None): self.img_labels = pd.read_csv(annotations_file) self.img_dir = img_dir self.transform = transform self.target_transform = target_transform def __len__(self): return len(self.img_labels) def __getitem__(self, idx): img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, 0]) image = decode_image(img_path) label = self.img_labels.iloc[idx, 1] if self.transform: image = self.transform(image) if self.target_transform: label = self.target_transform(label) return image, label
🌐
Skytowner
skytowner.com › explore › converting_column_type_to_integer_in_pandas_dataframe
Converting column type to integer in Pandas DataFrame
To convert the column type to integer in Pandas DataFrame, either use the Series' astype() method or use Pandas' to_numeric() method.