Machine Learning Crash Course | Google -前提条件和准备工作 Pandas

本文是Google的Machine Learning Crash Course的一部分,主要介绍了Pandas库的基础知识,包括Series和DataFrame数据结构,数据导入,访问和处理数据的方法,以及如何随机打乱数据的索引。此外,还提供了简单的练习和解决方案,帮助读者更好地理解和应用Pandas。
摘要由CSDN通过智能技术生成

前提条件和准备工作 | 机器学习速成课程 | Google Developers

Machine Learning Crash Course

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Pandas 简介

学习目标:
* 大致了解 pandas 库的 DataFrameSeries 数据结构
* 存取和处理 DataFrameSeries 中的数据
* 将 CSV 数据导入 pandas 库的 DataFrame
* 对 DataFrame 重建索引来随机打乱数据

pandas 是一种列存数据分析 API。它是用于处理和分析输入数据的强大工具,很多机器学习框架都支持将 pandas 数据结构作为输入。
虽然全方位介绍 pandas API 会占据很长篇幅,但它的核心概念非常简单,我们会在下文中进行说明。有关更完整的参考,请访问 pandas 文档网站,其中包含丰富的文档和教程资源。

基本概念

以下行导入了 pandas API 并输出了相应的 API 版本:

import pandas as pd
pd.__version__
u'0.22.0'

pandas 中的主要数据结构被实现为以下两类:

  • DataFrame,您可以将它想象成一个关系型数据表格,其中包含多个行和已命名的列。
  • Series,它是单一列。DataFrame 中包含一个或多个 Series,每个 Series 均有一个名称。

数据框架是用于数据操控的一种常用抽象实现形式。SparkR 中也有类似的实现。

创建 Series 的一种方法是构建 Series 对象。例如:

 pd.Series(['San Francisco', 'San Jose', 'Sacramento'])
0    San Francisco
1         San Jose
2       Sacramento
dtype: object
# 练习
pd.Series(['Mayi Si','Cao Cao','Liang Zhuge'])
0        Mayi Si
1        Cao Cao
2    Liang Zhuge
dtype: object

您可以将映射 string 列名称的 dict 传递到它们各自的 Series,从而创建DataFrame对象。如果 Series 在长度上不一致,系统会用特殊的 NA/NaN 值填充缺失的值。例如:

city_names = pd.Series(['San Francisco', 'San Jose', 'Sacramento'])
population = pd.Series([852469, 1015785, 485199]) # 对应城市人口

pd.DataFrame({ 'City name': city_names, 'Population': population })

City namePopulation
0San Francisco852469
1San Jose1015785
2Sacramento485199
# 练习
hero_names = pd.Series(['Mayi Si','Cao Cao','Liang Zhuge'])
smart_level = pd.Series([9, 7, 8]) 

pd.DataFrame({'Hero name': hero_names, 'Smart level': smart_level})
Hero nameSmart level
0Mayi Si9
1Cao Cao7
2Liang Zhuge8

但是在大多数情况下,您需要将整个文件加载到 DataFrame 中。下面的示例加载了一个包含加利福尼亚州住房数据的文件。请运行以下单元格以加载数据,并创建特征定义:

california_housing_dataframe = pd.read_csv("https://storage.googleapis.com/ml_universities/california_housing_train.csv", sep=",")
california_housing_dataframe.describe()
longitudelatitudehousing_median_agetotal_roomstotal_bedroomspopulationhouseholdsmedian_incomemedian_house_value
count17000.00000017000.00000017000.00000017000.00000017000.00000017000.00000017000.00000017000.00000017000.000000
mean-119.56210835.62522528.5893532643.664412539.4108241429.573941501.2219413.883578207300.912353
std2.0051662.13734012.5869372179.947071421.4994521147.852959384.5208411.908157115983.764387
min-124.35000032.5400001.0000002.0000001.0000003.0000001.0000000.49990014999.000000
25%-121.79000033.93000018.0000001462.000000297.000000790.000000282.0000002.566375119400.000000
50%-118.49000034.25000029.0000002127.000000434.0000001167.000000409.0000003.544600180400.000000
75%-118.00000037.72000037.0000003151.250000648.2500001721.000000605.2500004.767000265000.000000
max-114.31000041.95000052.00000037937.0000006445.00000035682.0000006082.00000015.000100500001.000000

上面的示例使用 DataFrame.describe 来显示关于 DataFrame 的有趣统计信息。另一个实用函数是 DataFrame.head,它显示 DataFrame 的前几个记录:

california_housing_dataframe.head()
longitudelatitudehousing_median_agetotal_roomstotal_bedroomspopulationhouseholdsmedian_incomemedian_house_value
0-114.3134.1915.05612.01283.01015.0472.01.493666900.0
1-114.4734.4019.07650.01901.01129.0463.01.820080100.0
2-114.5633.6917.0720.0174.0333.0117.01.650985700.0
3-114.5733.6414.01501.0337.0515.0226.03.191773400.0
4-114.5733.5720.01454.0326.0624.0262.01.925065500.0

pandas 的另一个强大功能是绘制图表。例如,借助 DataFrame.hist,您可以快速了解一个列中值的分布:

california_housing_dataframe.hist('housing_median_age')
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7f3924fa0f10>]],
      dtype=object)

这里写图片描述

california_housing_dataframe.hist('latitude')
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7f3922b32b50>]],
      dtype=object)

这里写图片描述

访问数据

您可以使用熟悉的 Python dict/list 指令访问 DataFrame 数据:

cities = pd.DataFrame({ 'City name': city_names, 'Population': population })
print type(cities['City name'])
cities['City name']
<class 'pandas.core.series.Series'>


0    San Francisco
1         San Jose
2       Sacramento
Name: City name, dtype: object
heros = pd.DataFrame({'Hero name':hero_names, 'Smart level': smart_level})
print type(heros['Hero name'])
heros['Hero name']
<class 'pandas.core.series.Series'>

0        Mayi Si
1        Cao Cao
2    Liang Zhuge
Name: Hero name, dtype: object
print type(cities['City name'][1])
cities['City name'][1]
<type 'str'>

'San Jose'
print type(heros['Smart level'][2])
heros['Smart level'][2]
<type 'numpy.int64'>

8
print type(cities[0:2])
cities[0:2]
print type(heros[0:2])
heros[0:1]

操控数据

您可以向 Series 应用 Python 的基本运算指令。例如:

population / 1000.
0     852.469
1    1015.785
2     485.199
dtype: float64

NumPy 是一种用于进行科学计算的常用工具包。pandas Series 可用作大多数 NumPy 函数的参数:

import numpy as np

np.log(population)
0    13.655892
1    13.831172
2    13.092314
dtype: float64
import numpy as np

np.log(smart_level)
0    2.197225
1    1.945910
2    2.079442
dtype: float64

对于更复杂的单列转换,您可以使用 Series.apply。像 Python 映射函数一样,Series.apply 将以参数形式接受 lambda 函数,而该函数会应用于每个值。

下面的示例创建了一个指明 population 是否超过 100 万的新 Series

population.apply(lambda val: val > 1000000)
0    False
1     True
2    False
dtype: bool
# 他们三个人的聪明水平是否超过 7
smart_level.apply(lambda val: val >7)
0     True
1    False
2     True
dtype: bool

DataFrames 的修改方式也非常简单。例如,以下代码向现有 DataFrame 添加了两个 Series

cities['Area square miles'] = pd.Series([46.87, 176.53, 97.92])
cities['Population density'] = cities['Population'] / cities['Area square miles']
cities
City namePopulationArea square milesPopulation density
0San Francisco85246946.8718187.945381
1San Jose1015785176.535754.177760
2Sacramento48519997.924955.055147
heros['Number'] = pd.Series([99, 88, 90])
heros['Hair'] = heros['Number'] * heros['Smart level']
heros
Hero nameSmart levelNumberHair
0Mayi Si999891
1Cao Cao788616
2Liang Zhuge890720

练习 1

通过添加一个新的布尔值列(当且仅当以下两项均为 True 时为 True)修改 cities 表格:

  • 城市以圣人命名。
  • 城市面积大于 50 平方英里。

注意:布尔值 Series 是使用“按位”而非传统布尔值“运算符”组合的。例如,执行逻辑与时,应使用 &,而不是 and

提示:“San” 在西班牙语中意为 “saint”。

# Your code here

cities['Analyze'] = cities['City name'].apply(lambda name:name.startswith('San')) & (cities['Area square miles'] > 50)
cities
City namePopulationArea square milesPopulation densityIs wide and has saint nameAnalyze
0San Francisco85246946.8718187.945381FalseFalse
1San Jose1015785176.535754.177760TrueTrue
2Sacramento48519997.924955.055147FalseFalse

解决方案

点击下方,查看解决方案。

cities['Is wide and has saint name'] = (cities['Area square miles'] > 50) & cities['City name'].apply(lambda name: name.startswith('San'))
cities
City namePopulationArea square milesPopulation densityIs wide and has saint name
0San Francisco85246946.8718187.945381False
1San Jose1015785176.535754.177760True
2Sacramento48519997.924955.055147False

索引

SeriesDataFrame 对象也定义了 index 属性,该属性会向每个 Series 项或 DataFrame 行赋一个标识符值。

默认情况下,在构造时,pandas 会赋可反映源数据顺序的索引值。索引值在创建后是稳定的;也就是说,它们不会因为数据重新排序而发生改变。

city_names.index
RangeIndex(start=0, stop=3, step=1)
cities.index
RangeIndex(start=0, stop=3, step=1)

调用 DataFrame.reindex 以手动重新排列各行的顺序。例如,以下方式与按城市名称排序具有相同的效果:

cities.reindex([2, 1, 0])
City namePopulationArea square milesPopulation densityIs wide and has saint nameAnalyze
2Sacramento48519997.924955.055147FalseFalse
1San Jose1015785176.535754.177760TrueTrue
0San Francisco85246946.8718187.945381FalseFalse

重建索引是一种随机排列 DataFrame 的绝佳方式。在下面的示例中,我们会取用类似数组的索引,然后将其传递至 NumPy 的 random.permutation 函数,该函数会随机排列其值的位置。如果使用此重新随机排列的数组调用 reindex,会导致 DataFrame 行以同样的方式随机排列。
尝试多次运行以下单元格!

cities.reindex(np.random.permutation(cities.index))
City namePopulationArea square milesPopulation densityIs wide and has saint nameAnalyze
0San Francisco85246946.8718187.945381FalseFalse
2Sacramento48519997.924955.055147FalseFalse
1San Jose1015785176.535754.177760TrueTrue

有关详情,请参阅索引文档

练习 2

reindex 方法允许使用未包含在原始 DataFrame 索引值中的索引值。请试一下,看看如果使用此类值会发生什么!您认为允许此类值的原因是什么?

# Your code here
cities.reindex([4, 0 ,3, 2, 1])
City namePopulationArea square milesPopulation densityIs wide and has saint nameAnalyze
4NaNNaNNaNNaNNaNNaN
0San Francisco852469.046.8718187.945381FalseFalse
3NaNNaNNaNNaNNaNNaN
2Sacramento485199.097.924955.055147FalseFalse
1San Jose1015785.0176.535754.177760TrueTrue

解决方案

点击下方,查看解决方案。

如果您的 reindex 输入数组包含原始 DataFrame 索引值中没有的值,reindex 会为此类“丢失的”索引添加新行,并在所有对应列中填充 NaN 值:

cities.reindex([0, 4, 5, 2])
City namePopulationArea square milesPopulation densityIs wide and has saint name
0San Francisco852469.046.8718187.945381False
4NaNNaNNaNNaNNaN
5NaNNaNNaNNaNNaN
2Sacramento485199.097.924955.055147False

这种行为是可取的,因为索引通常是从实际数据中提取的字符串(请参阅 pandas reindex 文档,查看索引值是浏览器名称的示例)。

在这种情况下,如果允许出现“丢失的”索引,您将可以轻松使用外部列表重建索引,因为您不必担心会将输入清理掉。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值