kagglePandas数据类型和缺失值
Introduction
在本教程中,您将学习如何研究 DataFrame 或 Series 中的数据类型。您还将学习如何查找和替换条目。
要开始此主题的练习,请点击此处。
Dtypes
DataFrame 或 Series 中列的数据类型称为 dtype。
您可以使用 dtype 属性获取特定列的类型。例如,我们可以获取 reviews DataFrame 中 price 列的 dtype:
import pandas as pd |
In [2]:
reviews.price.dtype |
Out[2]:
dtype('float64') |
或者,dtypes 属性返回 DataFrame 中每个列的 dtype:
In [3]:
reviews.dtypes |
Out[3]:
country object |
数据类型告诉我们 Pandas 内部是如何存储数据的。“float64”表示使用 64 位浮点数;“int64”表示使用相同大小的整数,等等。
需要注意的一个特点(这里展示得非常清楚)是,完全由字符串组成的列没有自己的类型;而是被赋予了“object”类型。
只要转换有意义,就可以使用“astype()”函数将一种类型的列转换为另一种类型。例如,我们可以将“points”列从其现有的“int64”数据类型转换为“float64”数据类型:
In [4]:
reviews.points.astype('float64') |
Out[4]:
0 87.0 |
DataFrame 或 Series 索引也有自己的 dtype:
In [5]:
reviews.index.dtype |
Out[5]:
dtype('int64') |
Pandas 还支持更多特殊数据类型,例如分类数据和时间序列数据。由于这些数据类型很少使用,我们将在本教程的后续章节中讨论它们。
Missing data
缺失值的条目会被赋值为 NaN,即“非数字”的缩写。由于技术原因,这些 NaN 值始终为 float64 数据类型。
Pandas 提供了一些专门用于缺失数据的方法。要选择 NaN 条目,您可以使用 pd.isnull()(或其配套函数 pd.notnull())。其用法如下:
In [6]:
reviews[pd.isnull(reviews.country)] |
Out[6]:
| country | description | designation | points | price | province | region_1 | region_2 | taster_name | taster_twitter_handle | title | variety | winery | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 913 | NaN | Amber in color, this wine has aromas of peach … | Asureti Valley | 87 | 30.0 | NaN | NaN | NaN | Mike DeSimone | @worldwineguys | Gotsa Family Wines 2014 Asureti Valley Chinuri | Chinuri | Gotsa Family Wines |
| 3131 | NaN | Soft, fruity and juicy, this is a pleasant, si… | Partager | 83 | NaN | NaN | NaN | NaN | Roger Voss | @vossroger | Barton & Guestier NV Partager Red | Red Blend | Barton & Guestier |
| … | … | … | … | … | … | … | … | … | … | … | … | … | … |
| 129590 | NaN | A blend of 60% Syrah, 30% Cabernet Sauvignon a… | Shah | 90 | 30.0 | NaN | NaN | NaN | Mike DeSimone | @worldwineguys | Büyülübağ 2012 Shah Red | Red Blend | Büyülübağ |
| 129900 | NaN | This wine offers a delightful bouquet of black… | NaN | 91 | 32.0 | NaN | NaN | NaN | Mike DeSimone | @worldwineguys | Psagot 2014 Merlot | Merlot | Psagot |
63 行 × 13 列
替换缺失值是一种常见的操作。Pandas 提供了一个非常便捷的方法来解决此问题:fillna()。fillna() 提供了几种不同的策略来缓解此类数据。例如,我们可以简单地将每个 NaN 替换为 "Unknown":
In [7]:
reviews.region_2.fillna("Unknown") |
Out[7]:
0 Unknown |
或者,我们可以用数据库中给定记录之后某个时间出现的第一个非空值来填充每个缺失值。这称为回填策略。
或者,我们可能有一个想要替换的非空值。例如,假设自此数据集发布以来,审阅者 Kerin O’Keefe 已将其 Twitter 帐号从“@kerinokeefe”更改为“@kerino”。在数据集中反映此情况的一种方法是使用“replace()”方法:
In [8]:
reviews.taster_twitter_handle.replace("@kerinokeefe", "@kerino") |
Out[8]:
0 @kerino |
这里值得一提的是 replace() 方法,因为它可以方便地替换数据集中被赋予某种标记值的缺失数据:例如 `“未知”、“未公开”、“无效”等等。
Your turn
如果你还没有开始练习,你可以**从这里开始**。
