对于第二个 Python Pandas 指南,我们将回顾如何导入数据,以及更深入地研究索引、比较语句和选择数据子集。为此,我们将使用包含来自Kaggle的可收养狗信息的数据集。他们有大量数据集,您可以轻松下载并用于项目。

从 csv 导入数据

首先,我们需要将下载的数据导入 DataFrame。使用 pd.read_csv 函数在本地工作时,从我们的下载文件夹上传数据非常简单。

dogs = pd.read_csv(r'Downloads/ShelterDogs.csv')

进入全屏模式 退出全屏模式

导入数据后,我们要检查 DataFrame 并确保它包含我们需要的所有信息并且格式正确。我们可以使用 .head() 查看前 5 行。

dogs.head()

进入全屏模式 退出全屏模式

[屏幕截图 2021-11-07 at 18.09.01.png](https://res.cloudinary.com/practicaldev/image/fetch/s--xhHPZjJQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto% 2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1636308553267/eXd2t9j9c.png)

为了了解有关每列数据类型的更多信息,我们可以使用 .info() 显示列名、包含空数据的行数以及每列的数据类型。

dogs.info()

进入全屏模式 退出全屏模式

[屏幕截图 2021-11-07 at 18.09.38.png](https://res.cloudinary.com/practicaldev/image/fetch/s--auJpaRKw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto% 2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1636308588956/VXK0rxapI.png)

数据类型

  • int - 整数

  • float - 十进制数

  • object - 一个字符串

更改数据类型

可能存在我们想要更改数据类型的实例,以执行某些操作或使它们更易于查看。

为了将字符串更改为数字,您可以使用 Pandas 方法 pd.to_numeric 或将数字更改为字符串,您可以使用 .astype(str)。

在我们的数据框中,我们还可以使用 .to_datetime 命令将日期列从字符串更改为实际的日期格式。

dogs['date_found'] = pd.to_datetime(dogs['date_found'])
dogs

进入全屏模式 退出全屏模式

[屏幕截图 2021-11-07 at 19.40.53.png](https://res.cloudinary.com/practicaldev/image/fetch/s--eVQa41nR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto% 2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1636314062876/wHx-FAI4g.png)

最后, .shape 将向我们显示列数,然后是行数。

dogs.shape

进入全屏模式 退出全屏模式

选择多列

要从 DataFrame 中选择两列或多列,我们可以在一对方括号之间使用列名列表。这将为我们提供数据的一个子集,并创建一个仅包含此信息的新 DataFrame,而我们的原始 DataFrame 保持不变。

type_breed = dogs[['name', 'sex', 'breed']]
type_breed.head()

进入全屏模式 退出全屏模式

[屏幕截图 2021-11-07 at 18.10.43.png](https://res.cloudinary.com/practicaldev/image/fetch/s--kK0TgSzJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto% 2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1636308652815/crsezoFiO.png)

使用 .iloc 选择一列

我们可以使用基于整数的 .iloc,通过指定要查看的行的位置索引来选择和显示单个列。

[屏幕截图 2021-10-31 at 14.24.13.png](https://res.cloudinary.com/practicaldev/image/fetch/s--M9LhiWhX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto% 2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1636314759657/bm__aTAPT.png)

dogs.iloc[1]

进入全屏模式 退出全屏模式

[屏幕截图 2021-11-07 at 18.11.24.png](https://res.cloudinary.com/practicaldev/image/fetch/s--TZzHG_N3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto% 2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1636308693583/Rg2FUR0A-.png)

iloc索引

在某些情况下,我们可能还想只选择某些行,我们可以通过使用行的索引来做到这一点,并使用 iloc 命令选择那些。它允许我们使用基于索引的选择来选择多行。这类似于我们使用 : 运算符和方括号从列表中选择元素的方式。

dogs.iloc[3:7]

进入全屏模式 退出全屏模式

[屏幕截图 2021-11-07 at 18.11.47.png](https://res.cloudinary.com/practicaldev/image/fetch/s--ii6xEBRI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto% 2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1636308725211/9YltEJXBy.png)

这将显示第 3-6 行,因为最后一行不包括在内。

: 运算符也来自原生 Python,意思是“一切”。但是,当与其他选择器结合使用时,它可以用来指示一系列值。

iloc[:10] 将选择第 10 行之前的所有行,但不包括第 10 行

dogs.iloc[:10]

进入全屏模式 退出全屏模式

我们也可以使用减号索引,例如 iloc[-2:] 将显示最后 2 列。

dogs.iloc[-2:]

进入全屏模式 退出全屏模式

重命名列

当我们从不同来源获取数据时,我们可能需要重命名列,以便它们更易于读取或调用。

有几种方法可以做到这一点,具体取决于我们要更改的列名。

  • .columns 将允许我们一次更改所有列。但是,重要的是要正确订购以避免贴错标签。

  • .rename 将允许我们更改单个列。您可以使用具有原始名称和新名称的字典传递单个列或多个列来更改。

dogs.rename(columns = {'posted' : 'date_posted', 
                         'breed' : 'dog_breed',
                         'adoptable_from' : 'date_adoptable',
                         'coat' : 'coat_type'},
                         inplace = True)

dogs.head()

进入全屏模式 退出全屏模式

[屏幕截图 2021-11-07 at 18.13.12.png](https://res.cloudinary.com/practicaldev/image/fetch/s--bgfxlM3r--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto% 2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1636308801538/JYZZxvSvH.png)

使用比较语句进行选择

我们还可以使用比较语句选择数据子集。

操作员

目的

\u003du003d

等于

!u003d

不相等

>

比...更棒

<

少于

>u003d

大于或等于

<u003d

小于或等于

等于

例如,如果我们只想显示数据集中的母狗,我们将使用双等号运算符并定义我们从中选择的列。

female = dogs[dogs.sex == 'female']
female

进入全屏模式 退出全屏模式

[屏幕截图 2021-11-07 at 18.14.11.png](https://res.cloudinary.com/practicaldev/image/fetch/s--SsQNmLC6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto% 2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1636308861068/gRD2OFDNo.png)

不等于

如果我们想排除所有未知混合品种的狗,我们可以使用不等于运算符来选择所有行,除了那些提到未知混合的行。

breeds = dogs[dogs.dog_breed != 'Unknown Mix']
breeds

进入全屏模式 退出全屏模式

[屏幕截图 2021-11-07 at 18.14.32.png](https://res.cloudinary.com/practicaldev/image/fetch/s--WsdlIGid--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto% 2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1636308894969/FyFMJg523.png)

大于

由于我们的数据集中有数字,我们可以使用大于运算符来选择任何包含大于我们给它的数字的行。我们只需要指定我们从哪一列中选择数据,在这种情况下,它是年龄列。

over_two = dogs[dogs.age > 2]
over_two

进入全屏模式 退出全屏模式

[屏幕截图 2021-11-07 at 18.15.09.png](https://res.cloudinary.com/practicaldev/image/fetch/s--YXRiNmpJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto% 2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1636308919299/3Taa6eCQs3.png)

小于

同样,我们可以使用小于运算符来选择所有年龄小于 4 岁的狗。

under_four = dogs[dogs.age < 4]
under_four

进入全屏模式 退出全屏模式

[屏幕截图 2021-11-07 at 18.15.49.png](https://res.cloudinary.com/practicaldev/image/fetch/s--QMXalvc8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto% 2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1636308959357/EVhW633mn.png)

多条语句

也可以在单个选择中使用多个比较运算符,我们可以定义是否希望最终数据集包含这两个,通过使用 & 符号来表示和规则。

likes_people = dogs[(dogs.likes_people == 'yes') & (dogs.likes_children == 'yes')]
likes_people

进入全屏模式 退出全屏模式

[屏幕截图 2021-11-07 at 18.16.27.png](https://res.cloudinary.com/practicaldev/image/fetch/s--1NXEyK7O--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto% 2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1636308996244/gIuVo7B3_.png)

此外,我们可以使用管道 | 来定义一个 or 规则,我们希望最终数据集在其中显示我们选择的任一数据点。

cats_female = dogs[(dogs.get_along_females == 'yes') | (dogs.get_along_cats == 'yes')]
cats_female

进入全屏模式 退出全屏模式

混合语句

我们还可以在一个语句中使用混合比较运算符,例如,如果我们想要任何已绝育且年龄在 4 岁或以上的狗,我们可以这样做:

suitable = dogs[(dogs.neutered == 'yes') & (dogs.age >= 4)]
suitable

进入全屏模式 退出全屏模式

[屏幕截图 2021-11-07 at 18.18.17.png](https://res.cloudinary.com/practicaldev/image/fetch/s--mp_8j-8U--/c_limit%2Cf_auto%2Cfl_progressive% 2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1636309109192/ljJVIqmaj.png)

内置选择器

Pandas 还附带了一些内置的条件选择器,可以以与逻辑语句类似的方式使用。

  • isin 选择值是您在列表中定义的数据

  • isnull 将选择您选择的列中为空的数据(即显示空)

  • notnull 选择有值的数据,即所有不为空的数据

isin

breed = dogs[(dogs.dog_breed.isin(['Staffordshire Terrier Mix', 'Labrador Retriever Mix', 'German Shepherd Dog Mix']))]
breed

进入全屏模式 退出全屏模式

[屏幕截图 2021-11-07 at 19.04.07.png](https://res.cloudinary.com/practicaldev/image/fetch/s--92YEUwag--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto% 2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1636311856198/3g-QybpgL.png)

一旦我们选择了数据子集,索引就会更改为仅反映我们选择的行,如果我们想适当地重新排序索引,我们将需要使用 .reset_index() 重置索引。

breed = dogs[(dogs.dog_breed.isin(['Staffordshire Terrier Mix', 'Labrador Retriever Mix', 'German Shepherd Dog Mix']))].reset_index()
breed 

进入全屏模式 退出全屏模式

[屏幕截图 2021-11-07 at 19.05.02.png](https://res.cloudinary.com/practicaldev/image/fetch/s--nVwYtOqM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto% 2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1636311911167/14MEpgc2i.png)

notnull

neutered_known = dogs.loc[dogs.neutered.notnull()]
neutered_known 

进入全屏模式 退出全屏模式

zwz 100129 zwz 100131 zwz 100132 zwz 100130 isnull

neutered_unknown = dogs.loc[dogs.neutered.isnull()]
neutered_unknown 

进入全屏模式 退出全屏模式

[屏幕截图 2021-11-07 at 19.07.06.png](https://res.cloudinary.com/practicaldev/image/fetch/s--KMOVA7X---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto %2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1636312036391/hUumXRusa.png)

处理空数据

在处理大数据集时,您可能会遇到空数据,这可能会在进行任何选择或数学运算时导致问题。它有时还会使表格看起来凌乱,难以查看,并且可能会扭曲最终结果。

有一种使用 Pandas 方法 .fillna() 替换空数据列的简单方法。在括号内,您需要添加一个参数来说明替换编号或文本。这将替换所有 Nan 字段。

dogs.fillna("not available")

进入全屏模式 退出全屏模式

[屏幕截图 2021-11-07 at 19.48.30.png](https://res.cloudinary.com/practicaldev/image/fetch/s--030WtKZh--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto% 2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1636314520992/JO3YdpS4Y.png)

我希望这是了解 Python 中更多 Pandas 库的一种有用(且可爱)的方式。我期待着在这个系列中再发几篇文章:)

可以在这里下载和玩的笔记本。

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐