Pandas - Series
In [20]:
#importing pandas and Series
import pandas as pd
from pandas import DataFrame, Series
In [21]:
#series from array
s=Series([10,20,30,40,50])
s1=Series([100,200,300,400,500])
print s
In [4]:
#series from dict
d={'a':10,'b':20,'c':30}
s=Series(d)
#dict keys are used for indexing notice NaN
print s
#creating a series from dict with cutom index
s=Series(d,index=['a','c','d'])
print s
In [5]:
#series from scalar values (index is required)
s=Series(4,index=[1,2,3,4],dtype=pd.Float64Index)
s
Out[5]:
In [6]:
#accessing elements from a series
s=Series([1,2,3,4,5,6,7,8,9,10])
#to get first element
print s[1:]
#to print elements from 1 -6
print s[1:7]
#printing last 3 element
print s[-3:]
#printing the last element
s.iloc[-3]
Out[6]:
In [11]:
#functions on series
s=Series([10,20,30,40,50])
#adding,subtracting, multiplying adn dividing from a series
print "Addition ",s.add(1)
print "Subtraction ",s.subtract(2)
print "Multiplication ",s.multiply(2)
print "Divide ",s.divide(2)
In [13]:
#Rolling Functions on Series
#gives cumulative difference of last n records
print "CUmulative Difference \n",s.diff(2)
#to calculate cumulative product
print "Cumulative Proudct\n",s.cumprod()
#to calculate cumulative sum
print "Cumulative Sum \n",s.cumsum()
#gives teh summary of the series
print "Basic info about the series \n",s.describe()
In [15]:
#applying a custom function
def custom_func(x):
return ((x*x)-1)
print "Custom Function ",s.apply(custom_func)
In [24]:
#to get a 2D matrix
print "Matrix from series\n",s.as_matrix()
#to perform autocorrelation
print "Autocorrelation is :",s.autocorr(4)
#to calculate the correlation between 2 series
print "Correlation is: ",s.corr(s1,'pearson')
#to find the covariance between two series
print "Covariance is : ",s.cov(s1,2)
In [28]:
#largest element
print "Index of largest element ",s.max()
#smallest element
print "Index of minimum element ",s.min()
#index of the largest element
print "Index of largest element ",s.argmax()
#index of the smallest element
print "Index of minimum element ",s.argmin()
#returns the indexes of the sorted array
print "Indexes of elements on a Series when sorted ",s.argsort()
Comments
Post a Comment