In this python pandas program, we will change the data type of given a column using pandas library.
Steps to solve the program
- Import pandas library as pd.
- Create a series using pd.Series().
- Change the data-type of the series from object to float using pd.to_numeric(series name, errors=’coerce’).
- It will convert all the non-string elements to float and if there is a string element it will show NaN instead.
- Print the output
import pandas as pd
df1 = pd.Series([54,27.90,'sqa',33.33,'tools'])
print("Original Data Series:")
print(df1)
print("Change the said data type to numeric:")
df2 = pd.to_numeric(df1, errors='coerce')
print(df2)
Output :
Original Data Series:
0 54
1 27.9
2 sqa
3 33.33
4 tools
dtype: object
Change the said data type to numeric:
0 54.00
1 27.90
2 NaN
3 33.33
4 NaN
dtype: float64