Python treats functions as objects which can simplify data cleaning. The following contains a transform utility class with two functions to clean strings:
%%file transform_util.py importreclassTransformUtil:@classmethoddefremove_punctuation(cls,value):"""Removes !, #, and ?. """returnre.sub('[!#?]','',value)@classmethoddefclean_strings(cls,strings,ops):"""General purpose method to clean strings. Pass in a sequence of strings and the operations to perform. """result=[]forvalueinstrings:forfunctioninops:value=function(value)result.append(value)returnresult
Overwriting transform_util.py
Below are nose tests that exercises the utility functions:
%%file tests/test_transform_util.py fromnose.toolsimportassert_equalfrom..transform_utilimportTransformUtilclassTestTransformUtil():states=[' Alabama ','Georgia!','Georgia','georgia', \ 'FlOrIda','south carolina##','West virginia?']expected_output=['Alabama','Georgia','Georgia','Georgia','Florida','South Carolina','West Virginia']deftest_remove_punctuation(self):assert_equal(TransformUtil.remove_punctuation('!#?'),'')deftest_map_remove_punctuation(self):# Map applies a function to a collectionoutput=map(TransformUtil.remove_punctuation,self.states)assert_equal('!#?'notinoutput,True)deftest_clean_strings(self):clean_ops=[str.strip,TransformUtil.remove_punctuation,str.title]output=TransformUtil.clean_strings(self.states,clean_ops)assert_equal(output,self.expected_output)
Overwriting tests/test_transform_util.py
Execute the nose tests in verbose mode:
!nosetests tests/test_transform_util.py -v
core.tests.test_transform_util.TestTransformUtil.test_clean_strings ... ok core.tests.test_transform_util.TestTransformUtil.test_map_remove_punctuation ... ok core.tests.test_transform_util.TestTransformUtil.test_remove_punctuation ... ok ---------------------------------------------------------------------- Ran 3 tests in 0.001s OK
Lambda functions are anonymous functions and are convenient for data analysis, as data transformation functions take functions as arguments.
Sort a sequence of strings by the number of letters:
strings=['foo','bar,','baz','f','fo','b','ba']strings.sort(key=lambdax:len(list(x)))strings
['f', 'b', 'fo', 'ba', 'foo', 'baz', 'bar,']
Closures are dynamically-genearated functions returned by another function. The returned function has access to the variables in the local namespace where it was created.
Closures are often used to implement decorators. Decorators are useful to transparently wrap something with additional functionality:
defmy_decorator(fun):defmyfun(*params,**kwparams):do_something()fun(*params,**kwparams)returnmyfun
Each time the following closure() is called, it generates the same output:
defmake_closure(x):defclosure():print('Secret value is: %s'%x)returnclosureclosure=make_closure(7)closure()
Secret value is: 7
Keep track of arguments passed:
defmake_watcher():dict_seen={}defwatcher(x):ifxindict_seen:returnTrueelse:dict_seen[x]=TruereturnFalsereturnwatcherwatcher=make_watcher()seq=[1,1,2,3,5,8,13,2,5,13][watcher(x)forxinseq]
[False, True, False, False, False, False, False, True, True, True]
*args and **kwargs are useful when you don't know how many arguments might be passed to your function or when you want to handle named arguments that you have not defined in advance.
Print arguments and call the input function on *args:
deffoo(func,arg,*args,**kwargs):print('arg: %s',arg)print('args: %s',args)print('kwargs: %s',kwargs)print('func result: %s',func(args))foo(sum,"foo",1,2,3,4,5)
('arg: %s', 'foo') ('args: %s', (1, 2, 3, 4, 5)) ('kwargs: %s', {}) ('func result: %s', 15)
Currying means to derive new functions from existing ones by partial argument appilcation. Currying is used in pandas to create specialized functions for transforming time series data.
The argument y in add_numbers is curried:
defadd_numbers(x,y):returnx+yadd_seven=lambday:add_numbers(7,y)add_seven(3)
10
The built-in functools can simplify currying with partial:
fromfunctoolsimportpartialadd_five=partial(add_numbers,5)add_five(2)
7
A generator is a simple way to construct a new iterable object. Generators return a sequence lazily. When you call the generator, no code is immediately executed until you request elements from the generator.
Find all the unique ways to make change for $1:
defsquares(n=5):forxinxrange(1,n+1):yieldx**2# No code is executedgen=squares()# Generator returns values lazilyforxinsquares():printx
1 4 9 16 25
A generator expression is analogous to a comprehension. A list comprehension is enclosed by [], a generator expression is enclosed by ():
gen=(x**2forxinxrange(1,6))forxingen:printx
1 4 9 16 25
The library itertools has a collection of generators useful for data analysis.
Function groupby takes a sequence and a key function, grouping consecutive elements in the sequence by the input function's return value (the key). groupby returns the function's return value (the key) and a generator.
importitertoolsfirst_letter=lambdax:x[0]strings=['foo','bar','baz']forletter,gen_namesinitertools.groupby(strings,first_letter):printletter,list(gen_names)
f ['foo'] b ['bar', 'baz']
itertools contains many other useful functions:
Function | Description |
---|---|
imap | Generator version of map |
ifilter | Generator version of filter |
combinations | Generates a sequence of all possible k-tuples of elements in the iterable, ignoring order |
permutations | Generates a sequence of all possible k-tuples of elements in the iterable, respecting order |
groupby | Generates (key, sub-iterator) for each unique key |