List in Pandas Series() in python by R4R Team

Series :
-series is one dimensional array defined in pandas library that can be used to store any data type.

Syntax-

pandas.Series(data,index)

Here data can be
1. scalar value like string,integer,float
2. python dictionary
3. Ndarray

-Here index part is optional, by default it is 0,1,2,3,4,......

List with Series()

program-

import pandas

#given list
list=[10,20,30,40,50,60]

#with default index
ans=pandas.Series(list)
print(ans)

#set index value alphabetically
ans=pandas.Series(list,index=['a','b','c','d','e','f'])
print(ans)


output-

010
120
230
340
450
560
dtype: int64
a10
b20
c30
d40
e50
f60
dtype: int64

-In this program, we pass a list in the Series() function of the pandas, then firstly it will return the list with default index,i.e. 0,1,2,3,4,5
-but in second part, we assign the index by programmer side,i.e. ['a','b','c','d','e'] then list will return with that index value as shown in above output.

What if index length and list length are not same like :

program-

import pandas

#given list of length 2
list=[10,20]

#index length is 4
i=['a','b','c','d']
ans=pandas.Series(list,index=i)
print(ans)


output-

.format(val=len(data), ind=len(index)))

ValueError: Length of passed values is 2, index implies 4

-In this program, we pass list with different length of index which is practically not possible so it will give an error which is shown in above output.




Leave a Comment: