CREATE, READ, UPDATE and DELETE in SERIES
In this tutorial, we are going to learn about CRUD operations in Series i.e. how to fetch data, update it and if necessary how to delete it.
Understanding CRUD in Series
The pandas series data structure enables us to perform CRUD operations, i.e. creating, reading, updating and deleting data. Once you perform these operations or a single operation on a series then a new series is returned.
CRUD: Creating a Series
Pandas Series can be created in different ways from MySQL table, through excel worksheet (CSV) or from an array, dictionary, list etc. Let’s look at how to create a series. Let’s import Pandas first into the python file or notebook that you are working in:
import pandas as pd ps = pd.Series([1,2,3,4,5]) print(ps)
Output:
0 1 1 2 2 3 3 4 4 5 dtype: int64
CRUD: Reading in Series
In order to read and select data from a series, you can use the index attribute by defining the index value or an index position (if no index is defined by you). Let’s select data through an index value, for example:
ps = pd.Series([1,2,3,4,5], index=['a','b','c','d','e']) print(ps['d'])
Output:
4
The above computation returned 4 which is a scalar value, however a series object will be returned if index values are repeated, for example:
ps = pd.Series([1,2,3,4,5], index=['a','d','c','d','e']) print(ps['d'])
Output:
d 2 d 4 dtype: int64
Above, you can see that index values (customized) have ‘d’ repeated twice and it returned the values in series located in those positions.
You can use a for loop as well to read the values in the Series, for example:
ps = pd.Series([1,2,3,4,5], index=['a','d','c','d','e']) for number in ps: print(number)
Output:Learning the Pandas Library: Python Tools for Data Munging, Analysis, and Visual
1 2 3 4 5
In order to print series values along with their indexes (both default or customized), use the .iteritems() which iterate over (index, value) tuples method in the for loop:
ps = pd.Series([1,2,3,4,5], index=['a','d','c','d','e']) for number in ps.iteritems(): print(number)
Output:
('a', 1) ('d', 2) ('c', 3) ('d', 4) ('e', 5)
CRUD: Updating in Series
You can update or replace the values in series as well by selecting the index position or value, for example:
ps = pd.Series([1,2,3,4,5], index=['a','d','c','d','e']) ps['d'] = 900 print(ps)
Output:
a 1 d 900 c 3 d 900 e 5 dtype: int64
You can use the set.value() method as well by setting the index separated by a comma with a new updated value in that index position. For example:
ps = pd.Series([1,2,3,4,5], index=['a','b','c','d','e']) ps.set_value('a', 2002) print(ps)
Output:
a 2002 b 2 c 3 d 4 e 5 dtype: int64
Note: the set_value() method is depreciated so it’s better to not put it in practice.
Deleting in Series
You can delete an entry in Series by selecting the del statement.
ps = pd.Series([1,2,3,4,5], index=['a','b','c','d','e']) del ps['a'] print(ps)
Output:
b 2 c 3 d 4 e 5 dtype: int64
References: