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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With