The Wayback Machine - https://web.archive.org/web/20240729001024/https://www.geeksforgeeks.org/data-structures-in-pandas/
Open In App

Data Structures in Pandas

Last Updated : 18 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Pandas is an open-source library that uses for working with relational or labeled data both easily and intuitively. It provides various data structures and operations for manipulating numerical data and time series. It offers a tool for cleaning and processes your data. It is the most popular Python library that is used for data analysis. In this article, We are going to learn about Pandas Data structure.

It supports two data structures:

Series

Pandas is a one-dimensional labeled array and capable of holding data of any type (integer, string, float, python objects, etc.)

Syntax: pandas.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)

Parameters:

  • data: array- Contains data stored in Series.
  • index: array-like or Index (1d)
  • dtype: str, numpy.dtype, or ExtensionDtype, optional
  • name: str, optional
  • copy: bool, default False

Example 1: Series holding the char data type.

Python3




import pandas as pd
  
# a simple char list
list = ['g', 'e', 'e', 'k', 's']
   
# create series form a char list
res = pd.Series(list)
print(res)


 
 

Output:

 

 

Example 2: Series holding the Int data type.

Python3




import pandas as pd
  
# a simple int list
list = [1,2,3,4,5]
   
# create series form a int list
res = pd.Series(list)
print(res)


 
 

Output:

 

 

Example 3: Series holding the dictionary.

Python3




import pandas as pd
 
dic = { 'Id': 1013, 'Name': 'MOhe',
       'State': 'Maniput','Age': 24}
 
res = pd.Series(dic)
print(res)


 
 

Output:

 

Dataframe

 

Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns like a spreadsheet or SQL table, or a dict of Series objects. . Pandas DataFrame consists of three principal components, the data, rows, and columns.

Creating a Pandas DataFrame

In the real world, a Pandas DataFrame will be created by loading the datasets from existing storage, storage can be SQL Database, CSV file, and Excel file. Pandas DataFrame can be created from the lists, dictionary, and from a list of dictionary etc. Dataframe can be created in different ways here are some ways by which we create a dataframe:

Example 1: DataFrame can be created using a single list or a list of lists.

Python3




# import pandas as pd
import pandas as pd
  
# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is',
            'portal', 'for', 'Geeks']
  
# Calling DataFrame constructor on list
df = pd.DataFrame(lst)
display(df)


 
 

Output:

 

 

Example 2: Creating DataFrame from dict of ndarray/lists. 

 To create DataFrame from dict of narray/list, all the narray must be of same length. If index is passed then the length index should be equal to the length of arrays. If no index is passed, then by default, index will be range(n) where n is the array length.

Python3




# Python code demonstrate creating
# DataFrame from dict narray / lists
# By default addresses.
  
import pandas as pd
  
# initialise data of lists.
data = {'Name':['Tom', 'nick', 'krish', 'jack'],
        'Age':[20, 21, 19, 18]}
  
# Create DataFrame
df = pd.DataFrame(data)
  
# Print the output.
display(df)


 
 

Output:

 

Dealing with a column and row in DataFrame

Selection of column: In Order to select a column in Pandas DataFrame, we can either access the columns by calling them by their columns name.

Python3




# Import pandas package
import pandas as pd
   
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],
        'Age':[27, 24, 22, 32],
        'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
        'Qualification':['Msc', 'MA', 'MCA', 'Phd']}
   
# Convert the dictionary into DataFrame 
df = pd.DataFrame(data)
   
# select two columns
print(df[['Name', 'Qualification']])


Output:

How to Select Rows and Column from Pandas DataFrame?

Example 1: Selecting rows.

pandas.DataFrame.loc is a function used to select rows from Pandas DataFrame based on the condition provided.

Syntax: df.loc[df[‘cname’] ‘condition’]

Parameters:

  • df: represents data frame
  • cname: represents column name
  • condition: represents condition on which rows has to be selected

Python3




# Importing pandas as pd
from pandas import DataFrame
   
# Creating a data frame
Data = {'Name': ['Mohe', 'Shyni', 'Parul', 'Sam'],
        'ID': [12, 43, 54, 32],
        'Place': ['Delhi', 'Kochi', 'Pune', 'Patna']
       }
   
df = DataFrame(Data, columns = ['Name', 'ID', 'Place'])
   
# Print original data frame
print("Original data frame:\n")
display(df)
   
# Selecting the product of Electronic Type
select_prod = df.loc[df['Name'] == 'Mohe']
   
print("\n")
   
# Print selected rows based on the condition
print("Selecting rows:\n")
display (select_prod)


Output:

Example 2: Selecting column.

Python3




# Importing pandas as pd
from pandas import DataFrame
   
# Creating a data frame
Data = {'Name': ['Mohe', 'Shyni', 'Parul', 'Sam'],
        'ID': [12, 43, 54, 32],
        'Place': ['Delhi', 'Kochi', 'Pune', 'Patna']
       }
   
df = DataFrame(Data, columns = ['Name', 'ID', 'Place'])
   
# Print original data frame
print("Original data frame:")
display(df)
   
print("Selected column: ")
display(df[['Name', 'ID']] )


 
 

Output:

 

 



Similar Reads

Converting nested JSON structures to Pandas DataFrames
In this article, we are going to see how to convert nested JSON structures to Pandas DataFrames. JSON with multiple levels In this case, the nested JSON data contains another JSON object as the value for some of its attributes. This makes the data multi-level and we need to flatten it as per the project requirements for better readability, as expla
3 min read
Inbuilt Data Structures in Python
Python has four non-primitive inbuilt data structures namely Lists, Dictionary, Tuple and Set. These almost cover 80% of the our real world data structures. This article will cover the above mentioned topics. Above mentioned topics are divided into four sections below. Lists: Lists in Python are one of the most versatile collection object types ava
3 min read
User Defined Data Structures in Python
In computer science, a data structure is a logical way of organizing data in computer memory so that it can be used effectively. A data structure allows data to be added, removed, stored and maintained in a structured manner. Python supports two types of data structures: Non-primitive data types: Python has list, set, and dictionary as its non-prim
4 min read
scipy.spatial - Spatial data structures and algorithms
In this article, we are going to see spatial data structure and algorithms, it is used to represent data in a geometric space. What is spatial data structure? The spatial package computes the triangulations, Voronoi diagrams, and convex hulls of a set of points, by leveraging the Qhull library. Moreover, it contains KDTree implementations for neare
2 min read
Internal implementation of Data Structures in Python
Python provides a variety of built-in data structures, each with its own characteristics and internal implementations optimized for specific use cases. In this article we are going to discuss about the most commonly used Data structures in Python and a brief overview of their internal implementations: Data Structure Internal Implementation Static o
3 min read
Learn DSA with Python | Python Data Structures and Algorithms
This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc, and some user-defined data structures such as linked lists, trees, graphs, etc, and traversal as well as searching and sorting algorithms with th
15+ min read
Python Data Structures
Data Structures are a way of organizing data so that it can be accessed more efficiently depending upon the situation. Data Structures are fundamentals of any programming language around which a program is built. Python helps to learn the fundamental of these data structures in a simpler way as compared to other programming languages. In this artic
15+ min read
Python | pandas.to_markdown() in Pandas
With the help of pandas.to_markdown() method, we can get the markdown table from the given dataframes by using pandas.to_markdown() method. Syntax : pandas.to_markdown() Return : Return the markdown table. Example #1 : In this example we can see that by using pandas.to_markdown() method, we are able to get the markdown table from the given datafram
1 min read
Python Pandas - pandas.api.types.is_file_like() Function
In this article, we will be looking toward the functionality of pandas.api.types.is_file_like() from the pandas.api.types module with its various examples in the Python language. An object must be an iterator AND have a read or write method as an attribute to be called file-like. It is important to note that file-like objects must be iterable, but
2 min read
Pandas DataFrame hist() Method | Create Histogram in Pandas
A histogram is a graphical representation of the numerical data. Sometimes you'll want to share data insights with someone, and using graphical representations has become the industry standard. Pandas.DataFrame.hist() function plots the histogram of a given Data frame. It is useful in understanding the distribution of numeric variables. This functi
4 min read
Practice Tags :
three90RightbarBannerImg