User-defined functions

from:https://campus.datacamp.com/courses/python-data-science-toolbox-part-1/writing-your-own-functions?ex=1

  • Strings in Python

To assign the string

company = 'DataCamp'

You've also learned to use the operations + and * with strings. Unlike with numeric types such as ints and floats, the + operator concatenates strings together, while the * concatenates multiple copies of a string together. In this exercise, you will use the + and * operations on strings to answer the question below. Execute the following code in the shell:

object1 = "data" + "analysis" + "visualization"
object2 = 1 * 3
object3 = "1" * 3

->object1 contains "dataanalysisvisualization"object2contains 3object3 contains "111".

  • Recapping built-in functions

  • Assign str(x) to a variable y1y1 = str(x)
  • Assign print(x) to a variable y2y2 = print(x)
  • Check the types of the variables xy1, and y2.

->x is a floaty1 is a str, and y2 is a NoneType.

It is important to remember that assigning a variable y2 to a function that prints a value but does not return a value will results in that variable y2 being oftype NoneType.

  • Write a simple function

You can use it as a pattern to define shout().

def square():
new_value = 4 ** 2
return new_value

# Define the function shout
def shout():
"""Print a string with three exclamation marks"""
# Concatenate the strings: shout_word
shout_word = 'congratulations'+ '!!!'

# Print shout_word
print(shout_word)

# Call shout
shout()

  • Single-parameter functions

You will now update shout() by adding a parameter so that it can accept and process any string argument passed to it.

# Define shout with the parameter, word
def shout(word):
"""Print a string with three exclamation marks"""
# Concatenate the strings: shout_word
shout_word = str(word) + '!!!'

# Print shout_word
print(shout_word)

# Call shout with the string 'congratulations'
shout('congratulations')

  • Functions that return single values

You're getting very good at this! Try your hand at another modification to the shout() function so that it now returns a single value instead of printing within the function. Recall that thereturn keyword lets you return values from functions.

# Define shout with the parameter, word
def shout(word):
"""Return a string with three exclamation marks"""
# Concatenate the strings: shout_word
shout_word = str(word) + '!!!'

# Replace print with return
return shout_word

# Pass 'congratulations' to shout: yell
yell = shout('congratulations')

# Print yell
print(yell)

Multiple parameters and return values

  • Functions with multiple parameters

Here, you will modify shout() to accept two arguments.

# Define shout with parameters word1 and word2
def shout(word1,word2):
"""Concatenate strings with three exclamation marks"""
# Concatenate word1 with '!!!': shout1
shout1 = word1 + '!!!'

# Concatenate word2 with '!!!': shout2
shout2 = word2 + '!!!'

# Concatenate shout1 with shout2: new_shout
new_shout = shout1 + shout2

# Return new_shout
return new_shout

# Pass 'congratulations' and 'you' to shout(): yell
yell = shout('congratulations', 'you')

# Print yell
print(yell)

  • A brief introduction to tuples

how to construct, unpack, and access tuple elements.

a, b, c = even_nums

# Unpack nums into num1, num2, and num3
print(nums)
num1, num2, num3 = (3, 4, 6)

# Construct even_nums
print(nums)
nums = (2, 4, 6)
print(nums)
even_nums = nums
print(even_nums)

  • Function that return multiple values

Here you will return multiple values from a function using tuples.

Note that the return statement return x, y has the same result as return (x, y): the former actually packs x and yinto a tuple under the hood!

# Define shout_all with parameters word1 and word2
def shout_all(word1, word2):

# Concatenate word1 with '!!!': shout1
shout1 = word1 + '!!!'

# Concatenate word2 with '!!!': shout2
shout2 = word2 + '!!!'

# Construct a tuple with shout1 and shout2: shout_words
shout_words = (shout1, shout2)

# Return shout_words
return shout_words

# Pass 'congratulations' and 'you' to shout_all(): yell1, yell2
yell1, yell2 = shout_all('congratulations','you')

# Print yell1 and yell2
print(yell1)
print(yell2)

Bringing it all together

  • Bringing it all together (1)

You've learned how to add parameters to your own function definitions, return a value or multiple values with tuples, and how to call the functions you've defined.

For this exercise, your goal is to recall how to load a dataset into a DataFrame. The dataset contains Twitter data and you will iterate over entries in a column to build a dictionary in which the keys are the names of languages and the values are the number of tweets in the given language. The file tweets.csv is available in your current directory.

# Import pandas
import pandas as pd

# Import Twitter data as DataFrame: df
df = pd.read_csv('tweets.csv')

# Initialize an empty dictionary: langs_count
langs_count = {}

# Extract column from DataFrame: col
col = df['lang']

# Iterate over lang column in DataFrame
for entry in col:

# If the language is in langs_count, add 1
if entry in langs_count.keys():
langs_count[entry] += 1
# Else add the language to langs_count, set the value to 1
else:
langs_count[entry] = 1

# Print the populated dictionary
print(langs_count)

Great job! You've now defined the functionality for iterating over entries in a column and building a dictionary with keys the names of languages and values the number of tweets in the given language.

  • Bringing it all together (2)

In this exercise, you will define a function with the functionality you developed in the previous exercise, return the resulting dictionary from within the function, and call the function with the appropriate arguments

For your convenience, the pandas package has been imported aspd and the 'tweets.csv' file has been imported into thetweets_df variable.

# Define count_entries()
def count_entries(df, col_name):
"""Return a dictionary with counts of
occurrences as value for each key."""

# Initialize an empty dictionary: langs_count
langs_count = {}

# Extract column from DataFrame: col
col = df[col_name]

# Iterate over lang column in DataFrame
for entry in col:

# If the language is in langs_count, add 1
if entry in langs_count.keys():
langs_count[entry] += 1
# Else add the language to langs_count, set the value to 1
else:
langs_count[entry] = 1

# Return the langs_count dictionary
return langs_count

# Call count_entries(): result
result = count_entries(tweets_df,'lang')

# Print the result
print(result)

Python Data Science Toolbox Part 1 Learning 1 - User-defined functions的更多相关文章

  1. python data science handbook1

    import numpy as np import matplotlib.pyplot as plt import seaborn; seaborn.set() rand = np.random.Ra ...

  2. 【转】The most comprehensive Data Science learning plan for 2017

    I joined Analytics Vidhya as an intern last summer. I had no clue what was in store for me. I had be ...

  3. 七个用于数据科学(data science)的命令行工具

    七个用于数据科学(data science)的命令行工具 数据科学是OSEMN(和 awesome 相同发音),它包括获取(Obtaining).整理(Scrubbing).探索(Exploring) ...

  4. Comprehensive learning path – Data Science in Python深入学习路径-使用python数据中学习

    http://blog.csdn.net/pipisorry/article/details/44245575 关于怎么学习python,并将python用于数据科学.数据分析.机器学习中的一篇非常好 ...

  5. 【转】Comprehensive learning path – Data Science in Python

    Journey from a Python noob to a Kaggler on Python So, you want to become a data scientist or may be ...

  6. Intermediate Python for Data Science learning 2 - Histograms

    Histograms from:https://campus.datacamp.com/courses/intermediate-python-for-data-science/matplotlib? ...

  7. 学习Data Science/Deep Learning的一些材料

    原文发布于我的微信公众号: GeekArtT. 从CFA到如今的Data Science/Deep Learning的学习已经有一年的时间了.期间经历了自我的兴趣.擅长事务的探索和试验,有放弃了的项目 ...

  8. R8:Learning paths for Data Science[continuous updating…]

    Comprehensive learning path – Data Science in Python Journey from a Python noob to a Kaggler on Pyth ...

  9. A Complete Tutorial to Learn Data Science with Python from Scratch

    A Complete Tutorial to Learn Data Science with Python from Scratch Introduction It happened few year ...

随机推荐

  1. 【CF802C】Heidi and Library (hard) 费用流

    [CF802C]Heidi and Library (hard) 题意:有n个人依次来借书,第i人来的时候要求书店里必须有种类为ai的书,种类为i的书要花费ci块钱购入.而书店的容量只有k,多余的书只 ...

  2. H5填坑笔记--持续更新

    最近一直在做移动端的页面,发现很多的坑,这里做一下总结,填填坑…… css常见的问题(一) 一.iOS键盘首字母自动大写 IOS的机子,默认英文输入法状态下,首字母是自动大写的,有时候挺烦人的. 在i ...

  3. [转]-[携程]-A Hybrid Collaborative Filtering Model with Deep Structure for Recommender Systems

    原文链接:推荐系统中基于深度学习的混合协同过滤模型 近些年,深度学习在语音识别.图像处理.自然语言处理等领域都取得了很大的突破与成就.相对来说,深度学习在推荐系统领域的研究与应用还处于早期阶段. 携程 ...

  4. windows下安装pytorch

    安装: https://blog.csdn.net/xiangxianghehe/article/details/80103095 Windows下通过pip安装PyTorch 0.4.0 impor ...

  5. TensorFlow 度量张量和张量或者和零之间的误差值

    用于一个回归任务或者正则问题 # l2损失,output= sum(x ** 2)/2 inputdata = tf.Variable(np.random.rand(2,3), dtype=np.fl ...

  6. CodeForces - 798D Mike and distribution 想法题,数学证明

    题意:给你两个数列a,b,你要输出k个下标,使得这些下标对应的a的和大于整个a数列的和的1/2.同时这些下标对应的b //题解:首先将条件换一种说法,就是要取floor(n/2)+1个数使得这些数大于 ...

  7. python面向对象高级:__slots__

    __slots__ 一个在有着数以千计的对象的类的时候节省内存的方法. 在Python中,每个类都有实例属性.默认情况下Python用一个字典来保存一个对象的实例属性.这非常有用,因为它允许我们在运行 ...

  8. Cache replacement policies 缓存实现算法

    Cache replacement policies - Wikipedia https://en.wikipedia.org/wiki/Cache_replacement_policies Cach ...

  9. XSS 防范XSS 攻击的措施

    XssSniper--0KEE TEAM               XssSniper--0KEE TEAM XssSniper 扩展介绍 一直以来,隐式输出的DomXSS漏洞难以被传统的扫描工具发 ...

  10. scrollView + tableview 上下滑动失效

    scrollView + tableview 上下滑动失效 控制器添加的  要加到子控制器,不然被销毁了 [self addChildViewController:chatVC];