
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
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 Articles
- Python Pandas - Plot multiple data columns in a DataFrame?
- Write a Python program to reshape a given dataframe in different ways
- Construct a DataFrame in Pandas using string data in Python
- Python - Convert Pandas DataFrame to binary data
- How to check the data type in pandas DataFrame?
- Python Pandas - Query the columns of a DataFrame
- Write a program in Python Pandas to convert a dataframe Celsius data column into Fahrenheit
- Python - Name columns explicitly in a Pandas DataFrame
- Python - Grouping columns in Pandas Dataframe
- Python - Replace values of a DataFrame with the value of another DataFrame in Pandas
- 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
- Python - Plot a Pandas DataFrame in a Line Graph
- Python – Strip whitespace from a Pandas DataFrame

Advertisements