Pandas Data Series: Change the data type of given a column or a Series
Write a Pandas program to change the data type of given a column or a Series.
Sample Series:
Original Data Series:
0 100
1 200
2 python
3 300.12
4 400
dtype: object
Change the said data type to numeric:
0 100.00
1 200.00
2 NaN
3 300.12
4 400.00
dtype: float64
Sample Solution :
Python Code :
import pandas as pd
s1 = pd.Series(['100', '200', 'python', '300.12', '400'])
print("Original Data Series:")
print(s1)
print("Change the said data type to numeric:")
s2 = pd.to_numeric(s1, errors='coerce')
print(s2)
Sample Output:
Original Data Series: 0 100 1 200 2 python 3 300.12 4 400 dtype: object Change the said data type to numeric: 0 100.00 1 200.00 2 NaN 3 300.12 4 400.00 dtype: float64
Explanation:
s1 = pd.Series(['100', '200', 'python', '300.12', '400']): This line creates a Pandas Series object 's1' containing a sequence of five string values: ['100', '200', 'python', '300.12', '400'].
s2 = pd.to_numeric(s1, errors='coerce'): This line applies the pd.to_numeric() function to the Series object 's1' with the 'errors' parameter set to 'coerce'. This function attempts to convert each value in the Series object to a numeric type (e.g., integer or float). If a value cannot be converted, it will be replaced with a NaN (not a number) value.
value in the Series object to a numeric type (e.g., integer or float). If a value cannot be converted, it will be replaced with a NaN (not a number) value.
The resulting Series object 's2' will have the same index as the original Series object 's1' but with numeric values where possible and NaN values where not possible.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Pandas program to convert a NumPy array to a Pandas series.
Next: Write a Python Pandas program to convert the first column of a DataFrame as a Series.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics