convert data to numeric in python

In Python, we can convert data to numeric by using the astype() method. This method is available for all pandas Series and DataFrame objects.

Let's say we have a DataFrame called df with a column called column_name that we want to convert to numeric type. We can use the following code:

main.py
df['column_name'] = df['column_name'].astype(float)
52 chars
2 lines

This will change the data in the column_name column to floating-point numbers. If we want to convert them to integers, we can use int instead of float.

If there are non-numeric values in the column, we can use the errors parameter of the astype() method to either raise an error or turn those values into NaN.

main.py
df['column_name'] = df['column_name'].astype(float, errors='raise')
68 chars
2 lines

This will raise a ValueError if there are non-numeric values in the column.

main.py
df['column_name'] = df['column_name'].astype(float, errors='coerce')
69 chars
2 lines

This will turn non-numeric values into NaN.

Note that if the astype() method fails to convert a value, it will raise an exception. If you want to handle these exceptions, you can use a try-except block.

gistlibby LogSnag