Pandas Series

Series is one dimensional labelled data structure. ( DataFrame is two dimensional )

Series can store string, integer and other python objects. It is like one column in a table. Syntax
pandas.Series(data=None, index=None, dtype=None, name=None, 
	copy=False, fastpath=False)
data : array like , iterable , dictionary, list, tuple , scalar
index : have the same length as data, Not necessarily unique,must be a hashable type
dtype : Data type of output series
name: Name given to series
copy: Default is false, Copy input data

Python Pandas library Series #02

Creating Series

Using List we can create one series
import pandas as pd
my_list=['Ravi','Raju','Alex']
s=pd.Series(data=my_list)
print(s)
Output
0    Ravi
1    Raju
2    Alex
We can add our index to this
my_list=['Ravi','Raju','Alex']
my_id=['p','q','r']
s=pd.Series(data=my_list,index=my_id)
print(s)
Output
p    Ravi
q    Raju
r    Alex
Using set as data source we can't create series as set is unordered.

Using tuple.
my_list=('Ravi','Raju','Alex')
s=pd.Series(data=my_list)
print(s)
Using dictionary as data source. Here dictionary keys are used as index.
my_dict={'a':'Ravi','b':'Raju','c':'Alex'}
s=pd.Series(data=my_dict)
print(s)
Output
a    Ravi
b    Raju
c    Alex
Only matching index are used.
my_dict={'a':'Ravi','b':'Raju','c':'Alex'}
s=pd.Series(data=my_dict,index=['a','c'])
print(s)
Output
a    Ravi    
c    Alex 
All unmatching index
my_dict={'a':'Ravi','b':'Raju','c':'Alex'}
s=pd.Series(data=my_dict,index=['x','y','z'])
print(s)
Output
x    NaN
y    NaN
z    NaN
Using Scalar value
s=pd.Series(data='Alex',index=['x','y','z'])
print(s)
Output
x    Alex
y    Alex
z    Alex

Using Numpy

We can create one dimensional numpy array.
import numpy as np
ar=np.random.rand(4) # Numpy array with random numbers 
s=pd.Series(ar)
print(s)

From DataFrame to Series

Pandas Series from DataFrame column

From DataFrame we can create Series by using columns. Read more on our sample student DataFrame. This sample DataFrame has 35 rows.
import pandas as pd 
df= pd.read_excel('D:\\my_data\\student.xlsx') # excel file 
df= pd.read_csv('D:\\my_data\\student.csv') # csv  file 
s=pd.Series(df['name']) # using name column data
print(s)
We can create a Series by using all columns of a DataFrame by converting the DataFrame to a list by using tolist()
s=pd.Series(df.values.tolist())
Sample output is here ( few records are shown, actual output will contain 35 records )
0        [1, John Deo, Four, 75, female]
1         [2, Max Ruin, Three, 85, male]
2           [3, Arnold, Three, 55, male]
3      [4, Krish Star, Four, 60, female]
----
----
31    [32, Binn Rott, Seven, 90, female]
32      [33, Kenn Rein, Six, 96, female]
33       [34, Gain Toe, Seven, 69, male]
34     [35, Rows Noump, Six, 88, female]

Accessing elements of a Series

Using head() and tail() ( above code with 35 records to be used )
print(s.head()) # First five records 
print(s.head(2)) # last  five records 
print(s.tail()) # last  five records 
print(s.tail(2)) # last  two records 
print(s[:5]) # first 5 records
Using iloc
print(s.iloc[3:7]) 
Output
3     Krish Star
4      John Mike
5      Alex John
6    My John Rob
print(s.iloc[:2].index.tolist()) #List of index of first two
print(s.iloc[:2].values.tolist()) #List of values of first two
Getting alternate rows
print(s.iloc[::2]) # alternate rows 
Using index position
my_dict={'a':'Ravi','b':'Raju','c':'Alex'}
s=pd.Series(data=my_dict)
print(s['b']) # Output:  Raju

Updating elements of series

my_dict={'a':'Ravi','b':'Raju','c':'Alex'}
s=pd.Series(data=my_dict)
s['b']='King' # updating using index 
print(s)
Output
a    Ravi
b    King
c    Alex

Converting Data type of Series

By default this will be inferred from data. Here the id column is integer so by default the dtype is integer (dtype: int64) . Here we have specified the dtype to be string. Check the output by removing dtype='string'.
How to create sample student DataFrame?
df= pd.read_csv('D:\\my_data\\student.csv') # csv  file 
s=pd.Series(df['id'],dtype='string')
print(s) # Name : id , dtype string
Use this sample series for all examples below.
import pandas as pd 
l1=[52,13,45,39] # List of values 
#l1=['One','Tow','Three','Four'] # List of values
my_id=['x','b','y','p'] # List of index 
s=pd.Series(l1,index=my_id) # create a series 
Apply function to increase the value of all elements
s=s.apply(lambda x:x+5) # operation on each element 
List of index of the series
print(s.index.tolist()) # List of index 
Value based on index
print(s['y']) # Key error if not found
print(s.sum()) # sum of all values / elements 
Find the maximum , minimum , median, mode of the series
print(s.min()) # use max(), mean(),median(),mode()
Sorting of values and index, use the options ascending, inplace, kind, na_position,ignore_index, Key
print(s.sort_values()) #
print(s.sort_index())
Delete one element using index. Watch the option inplace
s.drop(labels=['b'],inplace=True)
s.pop('x') # remove element using key
Adding element using index.
s['z']=50 # adding element using key
print(s.filter(items=['x','p'])) # searching based on key
Searching for values in a series.
print(s.isin([50,13])) # Matching True or False
#print(s[s.isin([50,13])]) # Matching row only
#print(s[s.isin([50,13])].tolist()) # Matching rows only
#print(s[s.isin([13,39])].index.tolist()) # Matching index or keys

to_numpy()

print(s.to_numpy()) # value to Numpy 
print(s.index.to_numpy()) # index to Numpy 
print(type(s.to_numpy())) # class 'numpy.ndarray'

Merging series

import pandas as pd
my_dict1={'a':300,'c':400}
my_dict2={'a':500,'c':200,'d':600}

s1=pd.Series(data=my_dict1)
s2=pd.Series(data=my_dict2)
#s=s1.combine(s2,max,fill_value=0)
s=s1.combine(s2,max)
print(s)
Output
a    500.0
c    400.0
d      NaN
dtype: float64
Questions.. Think... Pandas Pandas DataFrame
contains() to display and delete row based on Conditions
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer