- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a program in Python to covert the datatype of a particular column in a dataframe
Assume, you have a dataframe, the result for converting float to int as,
Before conversion Name object Age int64 Maths int64 Science int64 English int64 Result float64 dtype: object After conversion Name object Age int64 Maths int64 Science int64 English int64 Result int64 dtype: object
To solve this, we will follow the steps given below −
Solution
Define a dataframe
Convert float datatype column ‘Result’ into ‘int’ as follows −
df.Result.astype(int)
Example
Let’s see the below implementation to get a better understanding −
import pandas as pd data = {'Name': ['David', 'Adam', 'Bob', 'Alex', 'Serina'], 'Age' : [13,12,12,13,12], 'Maths': [98, 59, 66, 95, 70], 'Science': [75, 96, 55, 49, 78], 'English': [79, 45, 70, 60, 80], 'Result': [8.1,6.2,6.3,7.2,8.3]} df = pd.DataFrame(data) print("Before conversion\n", df.dtypes) df.Result = df.Result.astype(int) print("After conversion\n",df.dtypes)
Output
Name object Age int64 Maths int64 Science int64 English int64 Result float64 dtype: object Name object Age int64 Maths int64 Science int64 English int64 Result int64 dtype: object
Advertisements