Python Basics 2
Function, Nested Function, Lambda function, Error Handling
import pandas as pd
Functions
nums = (3,7,9) # tuple
num1, num2, num3 = nums
num1
3
# 함수 실행 결과를 tuple 로 리턴.
def divided(a, b):
x = a/b
y = a%b
shout_words = (x, y)
return shout_words
y = divided(10, 3)
y
(3.3333333333333335, 1)
# language count
tweets_df = pd.read_csv('data/tweets.csv')
tweets_df.head()
lang | source | |
---|---|---|
0 | en | twitter.com |
1 | en | myplume.com |
2 | et | twitter.com |
3 | en | twitter.com |
4 | en | myplume.com |
def count_entries(df, col_name):
langs_count = {}
col = df[col_name]
for entry in col:
if entry in langs_count.keys():
langs_count[entry] += 1
else:
langs_count[entry] = 1
return (langs_count)
result = count_entries(tweets_df, 'lang')
result
{'en': 222, 'et': 24, 'jp': 36, 'kr': 12, 'ru': 6}
Nested Functions
def echo(word1, word2, word3):
def inner(word):
return word * 3
return (inner(word1), inner(word2), inner(word3))
echo('a', 'b', 'c')
('aaa', 'bbb', 'ccc')
def necho(n):
def inner_echo(word):
return word * n
return inner_echo
func3 = necho(3)
func5 = necho(5)
print(func3('yap'), func5('wow!'))
yapyapyap wow!wow!wow!wow!wow!
variable-length arguments : (*args)
def gibberish(*args):
pak = ''
for word in args:
pak += word + ' '
return pak
one_word = gibberish('luke')
print(one_word)
luke
many_words = gibberish("luke", "leia", "han", "obi", "darth")
print(many_words)
luke leia han obi darth
def count_entries(df, *args):
cols_count = {}
for col_name in args:
col = df[col_name]
for entry in col:
if entry in cols_count.keys():
cols_count[entry] += 1
else:
cols_count[entry] = 1
return cols_count
result1 = count_entries(tweets_df, 'lang')
result1
{'en': 222, 'et': 24, 'jp': 36, 'kr': 12, 'ru': 6}
result2 = count_entries(tweets_df, 'lang', 'source')
result2
{'en': 222,
'et': 24,
'facebook.com': 30,
'jp': 36,
'kr': 12,
'myplume.com': 36,
'ru': 6,
'twitter.com': 234}
variable-length keyword arguments : (**kwargs)
def report_status(**kwargs):
for key, value in kwargs.items():
print(key + ": " + value)
print("\nEND REPORT")
report_status(name="luke", affiliation="jedi", status="missing")
name: luke
status: missing
affiliation: jedi
END REPORT
report_status(name="anakin", affiliation="sith lord", status="deceased")
name: anakin
status: deceased
affiliation: sith lord
END REPORT
# *args, *kwargs
def total(initial=5, *numbers, **keywords):
count = initial
for number in numbers: # 1, 2, 3
count += number
for key in keywords:
count += keywords[key] # vegetables=50, fruits=100
return count
total(10, 1, 2, 3, vegetables=50, fruits=100)
166
Lambda functions
points = [ { 'x' : 2, 'y' : 3 }, { 'x' : 4, 'y' : 1 }, { 'x' : 7, 'y' : 5 }, { 'x' : 9, 'y' : 2 } ]
points.sort(key=lambda i : i['y'])
points
[{'x': 4, 'y': 1}, {'x': 9, 'y': 2}, {'x': 2, 'y': 3}, {'x': 7, 'y': 5}]
echo_word = (lambda word, echo: word * echo)
result = echo_word('Hey', 5)
result
'HeyHeyHeyHeyHey'
fellowship = ['Frodo', 'Samwise', 'Merry', 'Aragorn', 'Legolas', 'Boromir', 'Gimli']
# map
result = map(lambda item: item + '~!!', fellowship)
result_list = list(result)
result_list
['Frodo~!!',
'Samwise~!!',
'Merry~!!',
'Aragorn~!!',
'Legolas~!!',
'Boromir~!!',
'Gimli~!!']
# filter
result = filter(lambda member: len(member) > 6, fellowship)
result_list = list(result)
result_list
['Samwise', 'Aragorn', 'Legolas', 'Boromir']
# reduce
from functools import reduce
result = reduce(lambda item1, item2: item1 + ' / ' + item2, fellowship)
result
'Frodo / Samwise / Merry / Aragorn / Legolas / Boromir / Gimli'
tweets_df = pd.read_csv('data/tweets.csv')
result = filter(lambda x: x[0:2] != 'tw', tweets_df['source'])
res_list = list(result)
res_list[0:20]
['myplume.com',
'myplume.com',
'facebook.com',
'facebook.com',
'myplume.com',
'myplume.com',
'myplume.com',
'myplume.com',
'facebook.com',
'facebook.com',
'facebook.com',
'myplume.com',
'myplume.com',
'facebook.com',
'facebook.com',
'myplume.com',
'myplume.com',
'myplume.com',
'myplume.com',
'facebook.com']
Error Handling
# try - except
def shout_echo(word, echo=1):
echo_word = ''
shout_words = ''
try:
echo_word = word * echo
shout_words = echo_word + '!!!'
except:
print("word must be a string and echo must be an integer.")
return shout_words
shout_echo("particle", echo="accelerator")
word must be a string and echo must be an integer.
''
# raise ValueError
def shout_echo(word, echo=1):
if echo < 0:
raise ValueError('echo must be greater than 0')
echo_word = word * echo
shout_word = echo_word + '!!!'
return shout_word
shout_echo("particle", echo=-1)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-39-b26be1fab645> in <module>()
----> 1 shout_echo("particle", echo=-1)
<ipython-input-38-ecd662da16f1> in shout_echo(word, echo)
2
3 if echo < 0:
----> 4 raise ValueError('echo must be greater than 0')
5
6 echo_word = word * echo
ValueError: echo must be greater than 0