pandas.Series(data=None, index=None, dtype=None, name=None,
copy=False, fastpath=False)
data
: array like , iterable , dictionary, list, tuple , scalarindex
: have the same length as data, Not necessarily unique,must be a hashable type dtype
: Data type of output seriesname
: Name given to seriescopy
: Default is false, Copy input data
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.
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
import numpy as np
ar=np.random.rand(4) # Numpy array with random numbers
s=pd.Series(ar)
print(s)
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]
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
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
dtype: int64
) . Here we have specified the dtype to be string. Check the output by removing dtype='string'
. 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
print(s.to_numpy()) # value to Numpy
print(s.index.to_numpy()) # index to Numpy
print(type(s.to_numpy())) # class 'numpy.ndarray'
Numpy to Pandas Interoperability Guide
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)
Outputa 500.0
c 400.0
d NaN
dtype: float64
Questions..
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.