Prev: The 'Series' object | Next: The 'DataFrame' object
import numpy as np
import pandas as pd
s = pd.Series([10,20,30,40,50], index = ['a','b','c','d','e'])
print(s)
print(s['c'])
x = s['c']+s['a']
print(x)
y = s[['b','e']]
print(y)
import numpy as np
import pandas as pd
data = {'a':1,
'b':2,
'c':3,
'd':4,
'e':5}
new_ind = ['A','B','C','D','E']
s = pd.Series(sorted(data.values()), index=new_ind)
print(s)
import numpy as np
import pandas as pd
data = {'a':1,
'b':2,
'c':3,
'd':4,
'e':5}
s = pd.Series(data)
print(s)
# Use rename() to change some of the current indexes
# Note that old indexes are mapped onto new indexes and a NEW Series is returned
s2 = s.rename({'a':'A', 'd':'D'})
print(s2)
import numpy as np
import pandas as pd
data = {'a':1,
'b':2,
'c':3,
'd':4,
'e':5}
s = pd.Series(data)
print(s)
old_ind = s.index # returns the list of s indexes
new_ind = list((''.join(s.index)).upper()) # returns list of s indexes in upper case
# rename() accepts a dict with zipped lists
# inplace = True defines that no new Series object will be constructed
s.rename(dict(zip(old_ind,new_ind)), inplace=True)
s
import numpy as np
import pandas as pd
data = {'a':1,
'b':2,
'c':3,
'd':4,
'e':5}
s = pd.Series(data)
print(s)
old_ind = s.index
added_ind = list((''.join(s.index)).upper())
new_ind = old_ind.union(added_ind) # lists 'old_ind' and 'added_ind' are united
snew = s.reindex(new_ind, fill_value='Unknown') # 'Unknown' is set for missing values
snew
In the following example, data alignment based on label indexes facilitates the addition of data between s1 and s2 series.
import numpy as np
import pandas as pd
s1 = pd.Series([10,20,30,40,50], index = ['a','b','c','d','e'], dtype='int')
s2 = pd.Series([5,10,15,20,25], index = ['e','d','c','b','a'], dtype='int')
print(s1)
print(s2)
s = s1+s2
s
import numpy as np
import pandas as pd
# Missing values are declared as 'None' in code
data = {'a':1,
'b':None,
'c':3,
'd':None,
'e':5}
s = pd.Series(data)
print(s,'\n')
print(s.isnull(),'\n')
print(s.notnull())
# Alternatively you may write:
# pd.isnull(s)
# pd.notnull(s)
import numpy as np
import pandas as pd
# Data: Unemployment percentages in various countries
un_data = {'Greece':27,
'Spain':21,
'Italy':20}
uns = pd.Series(un_data) # uns is a Series object based on un_data dictionary
print(uns, '\n')
uns.name='Unemployment' # Setting the Series 'name' property
uns.index.name='Countries' # Setting the Series 'index.name' property
inc_data = {'Spain':2.,
'Italy':-1.5,
'Greece':1.,
'Portugal':3.} # The label 'Portugal' is not included in the uns Series
incs = pd.Series(inc_data) # A new Series object (incs) is constructed here
sums = uns + incs # Adding the values of the two Series is no problem..
#..as data are automatically aligned
print(sums)
. Free learning material
. See full copyright and disclaimer notice