前提条件和准备工作 | 机器学习速成课程 | Google Developers
Copyright 2017 Google LLC.
# 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 库的 DataFrame
和 Series
数据结构
* 存取和处理 DataFrame
和 Series
中的数据
* 将 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
均有一个名称。
数据框架是用于数据操控的一种常用抽象实现形式。Spark 和 R 中也有类似的实现。
创建 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 name | Population | |
---|---|---|
0 | San Francisco | 852469 |
1 | San Jose | 1015785 |
2 | Sacramento | 485199 |
# 练习
hero_names = pd.Series(['Mayi Si',