Introduction

在本微课程中,您将全面了解最流行的 Python 数据分析库 **pandas**。

在此过程中,您将使用真实数据完成几个动手练习。我们建议您在阅读相应教程的同时完成练习。

要开始第一个练习,请点击此处

在本教程中,您将学习如何创建自己的数据,以及如何处理现有数据。

Getting started

要使用 pandas,通常需要从以下代码行开始。

In [1]:

import pandas as pd

Creating data

Pandas 中有两个核心对象:DataFrameSeries

DataFrame

DataFrame 是一个表。它包含一个由多个独立 条目 组成的数组,每个条目都有一个特定的 。每个条目对应一行(或 记录)和一列。

例如,考虑以下简单的 DataFrame:

In [2]:

pd.DataFrame({'Yes': [50, 21], 'No': [131, 2]})

Out[2]:

Yes No
0 50 131
1 21 2

在此示例中,“0,否”条目的值为 131。“0,是”条目的值为 50,依此类推。

DataFrame 条目不限于整数。例如,以下 DataFrame 的值是字符串:

In [3]:

pd.DataFrame({'Bob': ['I liked it.', 'It was awful.'], 'Sue': ['Pretty good.', 'Bland.']})

Out[3]:

Bob Sue
0 I liked it. Pretty good.
1 It was awful. Bland.

我们使用 pd.DataFrame() 构造函数来生成这些 DataFrame 对象。声明新 DataFrame 对象的语法是使用一个字典,其键是列名(本例中为 BobSue),值是条目列表。这是构造新 DataFrame 的标准方法,也是您最有可能遇到的方法。

字典列表构造函数会为 列标签 赋值,但 行标签 则使用从 0 开始的升序计数(0、1、2、3……)。有时这样做没问题,但很多时候我们需要自己赋值。

DataFrame 中使用的行标签列表称为 索引。我们可以在构造函数中使用 index 参数为其赋值:

In [4]:

pd.DataFrame({'Bob': ['I liked it.', 'It was awful.'], 
'Sue': ['Pretty good.', 'Bland.']},
index=['Product A', 'Product B'])

Out[4]:

Bob Sue
Product A I liked it. Pretty good.
Product B It was awful. Bland.

Series

相比之下,Series 是数据值的序列。如果说 DataFrame 是表,那么 Series 就是列表。实际上,你只需要一个列表就可以创建一个 Series:

In [5]:

pd.Series([1, 2, 3, 4, 5])

Out[5]:

0    1
1 2
2 3
3 4
4 5
dtype: int64

本质上,Series 是 DataFrame 中的一列。因此,你可以像之前一样,使用 index 参数为 Series 分配行标签。不过,Series 没有列名,只有一个通用的 name

In [6]:

pd.Series([30, 35, 40], index=['2015 Sales', '2016 Sales', '2017 Sales'], name='Product A')

Out[6]:

2015 Sales    30
2016 Sales 35
2017 Sales 40
Name: Product A, dtype: int64

Series 和 DataFrame 密切相关。可以把 DataFrame 想象成一堆“粘在一起”的 Series。我们将在本教程的下一部分中更详细地讲解这一点。

Reading data files

能够手动创建 DataFrame 或 Series 非常方便。但大多数情况下,我们实际上并不会手动创建自己的数据,而是使用已经存在的数据。

数据可以以多种不同的形式和格式存储。其中最基本的就是简单的 CSV 文件。打开 CSV 文件后,您会看到如下所示的内容:

Product A,Product B,Product C,
30,21,9,
35,34,1,
41,11,11

CSV 文件是一个用逗号分隔的值表。因此得名“逗号分隔值”,简称 CSV。

现在,让我们先把玩具数据集放在一边,看看将真实数据集读入 DataFrame 后是什么样子。我们将使用 pd.read_csv() 函数将数据读入 DataFrame。具体如下:

In [7]:

wine_reviews = pd.read_csv("../input/wine-reviews/winemag-data-130k-v2.csv")

我们可以使用“shape”属性来检查生成的DataFrame有多大:

In [8]:

wine_reviews.shape

Out[8]:

(129971, 14)

因此,我们的新 DataFrame 包含 13 万条记录,分布在 14 个不同的列中。这意味着近 200 万个条目!

我们可以使用 head() 命令检查生成的 DataFrame 的内容,该命令会抓取前五行:

In [9]:

wine_reviews.head()

Out[9]:

Unnamed: 0 country description designation points price province region_1 region_2 taster_name taster_twitter_handle title variety winery
0 0 Italy Aromas include tropical fruit, broom, brimston… Vulkà Bianco 87 NaN Sicily & Sardinia Etna NaN Kerin O’Keefe @kerinokeefe Nicosia 2013 Vulkà Bianco (Etna) White Blend Nicosia
1 1 Portugal This is ripe and fruity, a wine that is smooth… Avidagos 87 15.0 Douro NaN NaN Roger Voss @vossroger Quinta dos Avidagos 2011 Avidagos Red (Douro) Portuguese Red Quinta dos Avidagos
2 2 US Tart and snappy, the flavors of lime flesh and… NaN 87 14.0 Oregon Willamette Valley Willamette Valley Paul Gregutt @paulgwine Rainstorm 2013 Pinot Gris (Willamette Valley) Pinot Gris Rainstorm
3 3 US Pineapple rind, lemon pith and orange blossom … Reserve Late Harvest 87 13.0 Michigan Lake Michigan Shore NaN Alexander Peartree NaN St. Julian 2013 Reserve Late Harvest Riesling … Riesling St. Julian
4 4 US Much like the regular bottling from 2012, this… Vintner’s Reserve Wild Child Block 87 65.0 Oregon Willamette Valley Willamette Valley Paul Gregutt @paulgwine Sweet Cheeks 2012 Vintner’s Reserve Wild Child… Pinot Noir Sweet Cheeks

pd.read_csv() 函数功能强大,拥有超过 30 个可选参数可供指定。例如,您可以看到此数据集中的 CSV 文件有一个内置索引,而 Pandas 并未自动识别。为了让 Pandas 使用该列作为索引(而不是从头创建新索引),我们可以指定 index_col

In [10]:

wine_reviews = pd.read_csv("../input/wine-reviews/winemag-data-130k-v2.csv", index_col=0)
wine_reviews.head()

Out[10]:

country description designation points price province region_1 region_2 taster_name taster_twitter_handle title variety winery
0 Italy Aromas include tropical fruit, broom, brimston… Vulkà Bianco 87 NaN Sicily & Sardinia Etna NaN Kerin O’Keefe @kerinokeefe Nicosia 2013 Vulkà Bianco (Etna) White Blend Nicosia
1 Portugal This is ripe and fruity, a wine that is smooth… Avidagos 87 15.0 Douro NaN NaN Roger Voss @vossroger Quinta dos Avidagos 2011 Avidagos Red (Douro) Portuguese Red Quinta dos Avidagos
2 US Tart and snappy, the flavors of lime flesh and… NaN 87 14.0 Oregon Willamette Valley Willamette Valley Paul Gregutt @paulgwine Rainstorm 2013 Pinot Gris (Willamette Valley) Pinot Gris Rainstorm
3 US Pineapple rind, lemon pith and orange blossom … Reserve Late Harvest 87 13.0 Michigan Lake Michigan Shore NaN Alexander Peartree NaN St. Julian 2013 Reserve Late Harvest Riesling … Riesling St. Julian
4 US Much like the regular bottling from 2012, this… Vintner’s Reserve Wild Child Block 87 65.0 Oregon Willamette Valley Willamette Valley Paul Gregutt @paulgwine Sweet Cheeks 2012 Vintner’s Reserve Wild Child… Pinot Noir Sweet Cheeks

Your turn

如果你还没有开始练习,你可以**从这里开始**。