
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Reshape the data in a Pandas DataFrame
We can easily reshape the data by categorizing a specific column. Here, we will categorize the “Result”column i.e. Pass and Fail values in numbers form.
Import the required library −
import pandas as pd
Create a DataFrame with 2 columns −
dataFrame = pd.DataFrame( { "Student": ['Jack', 'Robin', 'Ted', 'Scarlett', 'Kat'],"Result": ['Pass', 'Fail', 'Fail', 'Pass', 'Pass'] } )
Reshape the data using the map() function and just set ‘Pass’ to 1 and ‘Fail’ to 0 −
dataFrame['Result'] = dataFrame['Result'].map({'Pass': 1,'Fail': 0, })
Example
Following is the code −
import pandas as pd # Create DataFrame dataFrame = pd.DataFrame( { "Student": ['Jack', 'Robin', 'Ted', 'Scarlett', 'Kat'],"Result": ['Pass', 'Fail', 'Fail', 'Pass', 'Pass'] } ) print"DataFrame ...\n",dataFrame # reshaping into numbers dataFrame['Result'] = dataFrame['Result'].map({'Pass': 1,'Fail': 0, }) print"\nReshaped DataFrame ...\n",dataFrame
Output
This will produce the following output
DataFrame ... Result Student 0 Pass Jack 1 Fail Robin 2 Fail Ted 3 Pass Scarlett 4 Pass Kat Reshaped DataFrame ... Result Student 0 1 Jack 1 0 Robin 2 0 Ted 3 1 Scarlett 4 1 Kat
- Related Questions & Answers
- Python – Merge two Pandas DataFrame
- Python – Strip whitespace from a Pandas DataFrame
- Python Pandas – Display all the column names in a DataFrame
- Python Pandas – Count the rows and columns in a DataFrame
- Python – Create a new column in a Pandas dataframe
- Compare specific Timestamps for a Pandas DataFrame – Python
- Write a Python program to reshape a given dataframe in different ways
- Create a Pivot Table as a DataFrame – Python Pandas
- Python Pandas - Plot multiple data columns in a DataFrame?
- Python Pandas – How to use Pandas DataFrame Property: shape
- Python Pandas – How to use Pandas DataFrame tail( ) function
- Python Pandas – Filter DataFrame between two dates
- Python Pandas – Get the datatype and DataFrame columns information
- Python - Convert Pandas DataFrame to binary data
- Python – Center align column headers of a Pandas DataFrame
Advertisements