Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a column of a pandas dataframe containing string values to int/float?

Tags:

python

pandas

svm

I have a pandas dataframe which contains a column that has non numeric values. How will I convert them to int/float values .

eq:

Col1       Col2

Lip_GD      267

Gly_hy_68   467

Hint_2      628

Jac+Jac     339

Lip_GD      234

Jac+Jac     267

How will I convert the column 1 to int when I read this data into a pandas dataframe?

like image 481
Krishna Avatar asked Oct 25 '25 02:10

Krishna


1 Answers

Create a mapping of each unique value in Col1 to an index value:

mapping = {k: v for v, k in enumerate(df.Col1.unique())}
>>> mapping
{'Gly_hy_68': 1, 'Hint_2': 2, 'Jac+Jac': 3, 'Lip_GD': 0}

Then create a new column mapping the values in Col1 back to their unique identifiers.

df['Col3'] = df.Col1.map(mapping)
>>> df
        Col1  Col2  Col3
0     Lip_GD   267     0
1  Gly_hy_68   467     1
2     Hint_2   628     2
3    Jac+Jac   339     3
4     Lip_GD   234     0
5    Jac+Jac   267     3
like image 121
Alexander Avatar answered Oct 26 '25 15:10

Alexander