pandas练习---应用Apply函数

古之立大事者,不惟有超世之才,亦必有坚忍不拔之志。这篇文章主要讲述pandas练习---应用Apply函数相关的知识,希望能为你提供帮助。
探索学生对酒的消费情况数据见github
步骤1 - 导入必要的库

import pandas as pd import numpy as np

步骤2 - 数据集
path4 = "./data/student-mat.csv"

步骤3 将数据命名为student
student = pd.read_csv(path4) student.head()

输出:
pandas练习---应用Apply函数

文章图片
pandas练习---应用Apply函数

文章图片

步骤4 从\'school\'到\'guardian\'将数据切片
stud_alcoh = student.loc[: , "school":"guardian"] stud_alcoh.head()

输出:
 
pandas练习---应用Apply函数

文章图片

步骤5  创建一个捕获字符串的lambda函数
captalizer = lambda x: x.upper()

步骤6  使\'Fjob\'列都大写
stud_alcoh[\'Fjob\'].apply(captalizer)

输出:
0TEACHER 1OTHER 2OTHER 3SERVICES 4OTHER 5OTHER 6OTHER 7TEACHER 8OTHER 9OTHER 10HEALTH 11OTHER 12SERVICES 13OTHER 14OTHER 15OTHER 16SERVICES 17OTHER 18SERVICES 19OTHER 20OTHER 21HEALTH 22OTHER 23OTHER 24HEALTH 25SERVICES 26OTHER 27SERVICES 28OTHER 29TEACHER ... 365OTHER 366SERVICES 367SERVICES 368SERVICES 369TEACHER 370SERVICES 371SERVICES 372AT_HOME 373OTHER 374OTHER 375OTHER 376OTHER 377SERVICES 378OTHER 379OTHER 380TEACHER 381OTHER 382SERVICES 383SERVICES 384OTHER 385OTHER 386AT_HOME 387OTHER 388SERVICES 389OTHER 390SERVICES 391SERVICES 392OTHER 393OTHER 394AT_HOME Name: Fjob, dtype: object

步骤7  打印数据集的最后几行元素
stud_alcoh.tail()

输出:
pandas练习---应用Apply函数

文章图片

步骤8  注意到原始数据框仍然是小写字母,接下来改进一下
stud_alcoh[\'Mjob\'] = stud_alcoh[\'Mjob\'].apply(captalizer) stud_alcoh[\'Fjob\'] = stud_alcoh[\'Fjob\'].apply(captalizer) stud_alcoh.tail()

输出:
pandas练习---应用Apply函数

文章图片

步骤9  创建一个名为majority的函数,它返回一个布尔值到一个名为legal_drinker的新列(多数年龄大于17岁)
def majority(x): if x > 17: return True else: return False

stud_alcoh[\'legal_drinker\'] = stud_alcoh[\'age\'].apply(majority) stud_alcoh.head()

输出:
pandas练习---应用Apply函数

文章图片

步骤10  将数据集的每个数字乘以10
def times10(x): if type(x) is int: return 10 * x return x

stud_alcoh.applymap(times10).head(10)

输出:
pandas练习---应用Apply函数

文章图片

参考链接:
1、http://pandas.pydata.org/pandas-docs/stable/cookbook.html#cookbook
【pandas练习---应用Apply函数】2、https://www.analyticsvidhya.com/blog/2016/01/12-pandas-techniques-python-data-manipulation/
3、https://github.com/guipsamora/pandas_exercises
 

    推荐阅读