Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you convert data frame column values to integer

Tags:

python

pandas

I need to convert data frame column to int.

df['Slot'].unique()

displays this:

array(['1', '2', '3', '4', 1, 3, 5], dtype=object)

some values have '' around it some dont.

I tried to convert the data type to int as below:

df['Slot']=df['Slot'].astype('Int64')

I get this error:

TypeError: cannot safely cast non-equivalent object to int64

Any ideas how to convert to int?

like image 886
user1471980 Avatar asked Jul 22 '26 22:07

user1471980


1 Answers

You should first convert to numeric, then cast to Int64:

df['Slot'] = pd.to_numeric(df['Slot']).astype('Int64')

After casting the type:

df.dtypes

Slot    Int64
dtype: object

As noted in comments, if you use numpy's int64 type this works from scratch:

df['Slot'].astype('int64')
like image 162
mozway Avatar answered Jul 25 '26 13:07

mozway



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!