Python Data Science Toolbox Part 1 Learning 1 - User-defined functions
User-defined functions
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"
, object2
contains 3
, object3
contains "111"
.
Recapping built-in functions
- Assign
str(x)
to a variabley1
:y1 = str(x)
- Assign
print(x)
to a variabley2
:y2 = print(x)
- Check the types of the variables
x
,y1
, andy2
.
->x
is a float
, y1
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 y
into 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的更多相关文章
- python data science handbook1
import numpy as np import matplotlib.pyplot as plt import seaborn; seaborn.set() rand = np.random.Ra ...
- 【转】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 ...
- 七个用于数据科学(data science)的命令行工具
七个用于数据科学(data science)的命令行工具 数据科学是OSEMN(和 awesome 相同发音),它包括获取(Obtaining).整理(Scrubbing).探索(Exploring) ...
- Comprehensive learning path – Data Science in Python深入学习路径-使用python数据中学习
http://blog.csdn.net/pipisorry/article/details/44245575 关于怎么学习python,并将python用于数据科学.数据分析.机器学习中的一篇非常好 ...
- 【转】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 ...
- Intermediate Python for Data Science learning 2 - Histograms
Histograms from:https://campus.datacamp.com/courses/intermediate-python-for-data-science/matplotlib? ...
- 学习Data Science/Deep Learning的一些材料
原文发布于我的微信公众号: GeekArtT. 从CFA到如今的Data Science/Deep Learning的学习已经有一年的时间了.期间经历了自我的兴趣.擅长事务的探索和试验,有放弃了的项目 ...
- 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 ...
- 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 ...
随机推荐
- 2016中国app年度排行榜:十大行业、25个领域、Top 500 和2017趋势预测
本文为猎豹全球智库联合猎豹移动大数据平台libra.科技顶尖媒体36kr联合发布,如需转载必须在文章开头注明“来源:猎豹全球智库”和作者姓名,且不得更改或增删文中所有信息. 本文作者:猎豹全球智库 容 ...
- 圆形CD绘制 (扇形)
参考: Egret教程Arc是使用示例:http://edn.egret.com/cn/article/index/id/673 我封装的工具类: /** * 圆形进度 * @author chenk ...
- windows桌面通知区域不显示音量图标的解决方法
在windows系统桌面通知区域一般都是显示的输入法.电源.网络.音量及托盘的应用程序等内容 通知区域图标显示与否与控制面板的通知区域图标的设置有关,我们有时会遇到通知区域不显示个别图标的情况,如不显 ...
- 【CF883B】Berland Army 拓扑排序
[CF883B]Berland Army 题意:给出n个点,m条有向边,有的点的点权已知,其余的未知,点权都在1-k中.先希望你确定出所有点的点权,满足: 对于所有边a->b,a的点权>b ...
- android极光杀掉程序收不到通知
http://docs.jpush.io/guideline/faq/#android 第三方系统收不到推送的消息 由于第三方 ROM 的管理软件需要用户手动操作 小米[MIUI] 自启动管理:需要把 ...
- [励志英语片段]practicing deliberately
最近看到一篇鸡汤文,觉得措词造句皆为吾辈所能接受,以后可以用作写作或口语素材~ 文章中心思想:同样是训练100小时,结果可以大不一样~所以不要用时间来欺骗自己. Consider the activi ...
- Python 核心编程
第3章 Python 基础 1.语句和语法: 注释(#): 继续换句话说跨行(\):有两种例外情况一个语句不使用反斜线也可以跨行.在使用闭合操作符时,单一语句可以跨多行,如小括号.中括号,花括号等,另 ...
- xtrabackup安装部署(二)
在官网中,复制相关链接下载最新版本(建议使用当前发布版本前6个月左右的稳定版本) https://www.percona.com/downloads/XtraBackup/LATEST/ 1.下载和安 ...
- numpy的文件存储 .npy .npz 文件
1)Numpy能够读写磁盘上的文本数据或二进制数据.将数组以二进制格式保存到磁盘np.load和np.save是读写磁盘数组数据的两个主要函数,默认情况下,数组是以未压缩的原始二进制格式保存在扩展名为 ...
- 2018/03/19 每日一个Linux命令 之 touch
touch 英文翻译为 触碰 很形象 touch [文件] 就像我就碰你一下,什么都不干..... 如果没有这个文件则我就新建这个文件 会修改这个文件的最后修改时间 没有的话则会产生一个0字节大小的空 ...