博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Pandas教程:使用Python进行数据分析:第1部分
阅读量:2520 次
发布时间:2019-05-11

本文共 36355 字,大约阅读时间需要 121 分钟。

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. is one of those packages, and makes importing and analyzing data much easier. Pandas builds on packages like and to give you a single, convenient, place to do most of your data analysis and visualization work.

Python是进行数据分析的一种出色语言,主要是因为以数据为中心的Python软件包拥有一个奇妙的生态系统。 是其中的一种,使导入和分析数据更加容易。 Pandas建立在和类的软件包的基础上,为您提供一个方便,方便的地方来进行大多数数据分析和可视化工作。

In this introduction, we’ll use Pandas to analyze data on video game reviews from , a popular video game review site. The data was scraped by , and can be found . As we analyze the video game reviews, we’ll learn key Pandas concepts like indexing.

在本简介中,我们将使用Pandas分析来自流行视频游戏评论网站的视频游戏评论数据。 数据由 ,可以在找到。 在分析视频游戏评论时,我们将学习熊猫的关键概念,例如索引。

Do games like the Witcher 3 tend to get better reviews on the PS4 than the Xbox One? This dataset can help us find out.

像《巫师3》这样的游戏是否在PS4上获得比Xbox One更好的评论? 该数据集可以帮助我们找出答案。

Just as a note, we’ll be using and to do our analysis.

请注意,我们将使用和进行分析。

用熊猫导入数据 (Importing Data with Pandas)

The first step we’ll take is to read the data in. The data is stored as a , or csv, file, where each row is separated by a new line, and each column by a comma (,). Here are the first few rows of the ign.csv file:

我们将采取的第一步是读取数据。数据以或csv文件存储,其中每行用换行分隔,每列用逗号( , )分隔。 以下是ign.csv文件的前几行:

,score_phrase,title,url,platform,score,genre,editors_choice,release_year,release_month,release_day0,Amazing,LittleBigPlanet PS Vita,/games/littlebigplanet-vita/vita-98907,PlayStation Vita,9.0,Platformer,Y,2012,9,121,Amazing,LittleBigPlanet PS Vita -- Marvel Super Hero Edition,/games/littlebigplanet-ps-vita-marvel-super-hero-edition/vita-20027059,PlayStation Vita,9.0,Platformer,Y,2012,9,122,Great,Splice: Tree of Life,/games/splice/ipad-141070,iPad,8.5,Puzzle,N,2012,9,123,Great,NHL 13,/games/nhl-13/xbox-360-128182,Xbox 360,8.5,Sports,N,2012,9,11,score_phrase,title,url,platform,score,genre,editors_choice,release_year,release_month,release_day0,Amazing,LittleBigPlanet PS Vita,/games/littlebigplanet-vita/vita-98907,PlayStation Vita,9.0,Platformer,Y,2012,9,121,Amazing,LittleBigPlanet PS Vita -- Marvel Super Hero Edition,/games/littlebigplanet-ps-vita-marvel-super-hero-edition/vita-20027059,PlayStation Vita,9.0,Platformer,Y,2012,9,122,Great,Splice: Tree of Life,/games/splice/ipad-141070,iPad,8.5,Puzzle,N,2012,9,123,Great,NHL 13,/games/nhl-13/xbox-360-128182,Xbox 360,8.5,Sports,N,2012,9,11

As you can see above, each row in the data represents a single game that was reviewed by IGN. The columns contain information about that game:

正如您在上面看到的,数据中的每一行代表一个由IGN审核的游戏。 这些列包含有关该游戏的信息:

  • score_phrase – how IGN described the game in one word. This is linked to the score it received.
  • title – the name of the game.
  • url – the URL where you can see the full review.
  • platform – the platform the game was reviewed on (PC, PS4, etc).
  • score – the score for the game, from 1.0 to 10.0.
  • genre – the genre of the game.
  • editors_choiceN if the game wasn’t an editor’s choice, Y if it was. This is tied to score.
  • release_year – the year the game was released.
  • release_month – the month the game was released.
  • release_day – the day the game was released.
  • score_phrase – IGN如何用一个词形容游戏。 这链接到它收到的分数。
  • title –游戏名称。
  • url –您可以在其中查看完整评论的URL。
  • platform –审查游戏的平台(PC,PS4等)。
  • score –游戏的得分,从1.010.0
  • genre –游戏的体裁。
  • editors_choice –如果游戏不是编辑选择, editors_choice N否则为Y 这与得分息息相关。
  • release_year –游戏发布的年份。
  • release_month –游戏发布的月份。
  • release_day –游戏发布的日期。

There’s also a leading column that contains row index values. We can safely ignore this column, but we’ll dive into what index values are later on. In order to be able to work with the data in Python, we’ll need to read the csv file into a . A DataFrame is a way to represent and work with tabular data. Tabular data has rows and columns, just like our csv file.

还有一个前导列,其中包含行索引值。 我们可以放心地忽略此列,但稍后将深入探讨哪些索引值。 为了能够使用Python中的数据,我们需要将csv文件读取到 。 DataFrame是表示和使用表格数据的一种方式。 表格数据具有行和列,就像我们的csv文件一样。

In order to read in the data, we’ll need to use the function. This function will take in a csv file and return a DataFrame. The below code will:

为了读入数据,我们需要使用函数。 此函数将接收一个csv文件并返回一个DataFrame。 下面的代码将:

  • Import the pandas library. We rename it to pd so it’s faster to type out.
  • Read ign.csv into a DataFrame, and assign the result to reviews.
  • 导入pandas库。 我们将其重命名为pd这样可以更快地进行输入。
  • 阅读ign.csv成数据帧,并分配结果reviews

Once we read in a DataFrame, Pandas gives us two methods that make it fast to print out the data. These functions are:

读取DataFrame后,Pandas为我们提供了两种方法,可以快速打印出数据。 这些功能是:

We’ll use the head method to see what’s in reviews:

我们将使用head方法查看reviews

reviewsreviews .. headhead ()()
Unnamed: 0 未命名:0 score_phrase score_phrase title 标题 url 网址 platform 平台 score 得分 genre 类型 editors_choice editors_choice release_year release_year release_month release_month release_day release_day
0 0 0 0 Amazing 惊人 LittleBigPlanet PS Vita LittleBigPlanet PS Vita /games/littlebigplanet-vita/vita-98907 / games / littlebigplanet-vita / vita-98907 PlayStation Vita PlayStation Vita 9.0 9.0 Platformer 平台游戏 Y ÿ 2012 2012年 9 9 12 12
1 1个 1 1个 Amazing 惊人 LittleBigPlanet PS Vita — Marvel Super Hero E… LittleBigPlanet PS Vita —惊奇超级英雄E… /games/littlebigplanet-ps-vita-marvel-super-he… / games / littlebigplanet-ps-vita-marvel-super-he… PlayStation Vita PlayStation Vita 9.0 9.0 Platformer 平台游戏 Y ÿ 2012 2012年 9 9 12 12
2 2 2 2 Great Splice: Tree of Life 拼接:生命之树 /games/splice/ipad-141070 / games / splice / ipad-141070 iPad 的iPad 8.5 8.5 Puzzle 难题 N ñ 2012 2012年 9 9 12 12
3 3 3 3 Great NHL 13 NHL 13 /games/nhl-13/xbox-360-128182 / games / nhl-13 / xbox-360-128182 Xbox 360 Xbox 360 8.5 8.5 Sports 体育 N ñ 2012 2012年 9 9 11 11
4 4 4 4 Great NHL 13 NHL 13 /games/nhl-13/ps3-128181 / games / nhl-13 / ps3-128181 PlayStation 3 的PlayStation 3 8.5 8.5 Sports 体育 N ñ 2012 2012年 9 9 11 11

We can also access the property to see row many rows and columns are in reviews:

我们还可以访问属性,以查看reviews行,行和列:

(18625, 11)

As you can see, everything has been read in properly – we have 18625 rows and 11 columns.

如您所见,所有内容均已正确读取-我们有18625行和11列。

One of the big advantages of Pandas vs just using NumPy is that Pandas allows you to have columns with different data types. reviews has columns that store float values, like score, string values, like score_phrase, and integers, like release_year.

与仅使用NumPy相比,Pandas的一大优点是Pandas允许您使用具有不同数据类型的列。 reviews列存储浮点值(例如score ,字符串值(例如score_phrase )和整数(例如release_year

Now that we’ve read the data in properly, let’s work on indexing reviews to get the rows and columns that we want.

现在,我们已经在读的正确数据,让我们对索引工作reviews来获得我们想要的行和列。

用Pandas索引数据帧 (Indexing DataFrames with Pandas)

Earlier, we used the head method to print the first 5 rows of reviews. We could accomplish the same thing using the method. The iloc method allows us to retrieve rows and columns by position. In order to do that, we’ll need to specify the positions of the rows that we want, and the positions of the columns that we want as well.

之前,我们使用head方法打印reviews的前5行。 我们可以使用方法完成同样的事情。 iloc方法允许我们按位置检索行和列。 为此,我们需要指定所需行的位置以及所需列的位置。

The below code will replicate reviews.head():

以下代码将复制reviews.head()

reviewsreviews .. ilociloc [[ 00 :: 55 ,:],:]
Unnamed: 0 未命名:0 score_phrase score_phrase title 标题 url 网址 platform 平台 score 得分 genre 类型 editors_choice editors_choice release_year release_year release_month release_month release_day release_day
0 0 0 0 Amazing 惊人 LittleBigPlanet PS Vita LittleBigPlanet PS Vita /games/littlebigplanet-vita/vita-98907 / games / littlebigplanet-vita / vita-98907 PlayStation Vita PlayStation Vita 9.0 9.0 Platformer 平台游戏 Y ÿ 2012 2012年 9 9 12 12
1 1个 1 1个 Amazing 惊人 LittleBigPlanet PS Vita — Marvel Super Hero E… LittleBigPlanet PS Vita —惊奇超级英雄E… /games/littlebigplanet-ps-vita-marvel-super-he… / games / littlebigplanet-ps-vita-marvel-super-he… PlayStation Vita PlayStation Vita 9.0 9.0 Platformer 平台游戏 Y ÿ 2012 2012年 9 9 12 12
2 2 2 2 Great Splice: Tree of Life 拼接:生命之树 /games/splice/ipad-141070 / games / splice / ipad-141070 iPad 的iPad 8.5 8.5 Puzzle 难题 N ñ 2012 2012年 9 9 12 12
3 3 3 3 Great NHL 13 NHL 13 /games/nhl-13/xbox-360-128182 / games / nhl-13 / xbox-360-128182 Xbox 360 Xbox 360 8.5 8.5 Sports 体育 N ñ 2012 2012年 9 9 11 11
4 4 4 4 Great NHL 13 NHL 13 /games/nhl-13/ps3-128181 / games / nhl-13 / ps3-128181 PlayStation 3 的PlayStation 3 8.5 8.5 Sports 体育 N ñ 2012 2012年 9 9 11 11

As you can see above, we specified that we wanted rows 0:5. This means that we wanted the rows from position 0 up to, but not including, position 5. The first row is considered to be in position 0. This gives us the rows at positions 0, 1, 2, 3, and 4.

正如您在上面看到的,我们指定了要0:5行。 这意味着我们想要从位置0到但不包括位置5 。 第一行被认为是在位置0 。 这给我们的位置处的行0123 ,和4

If we leave off the first position value, like :5, it’s assumed we mean 0. If we leave off the last position value, like 0:, it’s assumed we mean the last row or column in the DataFrame.

如果我们忽略第一个位置值,例如:5 ,则假定我们的意思是0 。 如果我们忽略了最后一个位置值(例如0: :),则假定我们是指DataFrame中的最后一行或最后一列。

We wanted all of the columns, so we specified just a colon (:), without any positions. This gave us the columns from 0 to the last column.

我们希望所有的列,所以我们只指定了一个冒号( : ),没有任何职位。 这给了我们从0到最后一列的列。

Here are some indexing examples, along with the results:

以下是一些索引示例以及结果:

  • reviews.iloc[:5,:] – the first 5 rows, and all of the columns for those rows.
  • reviews.iloc[:,:] – the entire DataFrame.
  • reviews.iloc[5:,5:] – rows from position 5 onwards, and columns from position 5 onwards.
  • reviews.iloc[:,0] – the first column, and all of the rows for the column.
  • reviews.iloc[9,:] – the 10th row, and all of the columns for that row.
  • reviews.iloc[:5,:] –前5行,以及这些行的所有列。
  • reviews.iloc[:,:] –整个DataFrame。
  • reviews.iloc[5:,5:] -从位置行5起,并从位置列5起。
  • reviews.iloc[:,0] –第一列,以及该列的所有行。
  • reviews.iloc[9,:] –第十行,以及该行的所有列。

Indexing by position is very similar to indexing. If you want to learn more, you can read our NumPy tutorial .

按位置索引与索引非常相似。 如果您想了解更多信息,可以阅读我们的NumPy教程。

Now that we know how to index by position, let’s remove the first column, which doesn’t have any useful information:

现在我们知道了如何按位置索引,让我们删除第一列,该列没有任何有用的信息:

score_phrase score_phrase title 标题 url 网址 platform 平台 score 得分 genre 类型 editors_choice editors_choice release_year release_year release_month release_month release_day release_day
0 0 Amazing 惊人 LittleBigPlanet PS Vita LittleBigPlanet PS Vita /games/littlebigplanet-vita/vita-98907 / games / littlebigplanet-vita / vita-98907 PlayStation Vita PlayStation Vita 9.0 9.0 Platformer 平台游戏 Y ÿ 2012 2012年 9 9 12 12
1 1个 Amazing 惊人 LittleBigPlanet PS Vita — Marvel Super Hero E… LittleBigPlanet PS Vita —惊奇超级英雄E… /games/littlebigplanet-ps-vita-marvel-super-he… / games / littlebigplanet-ps-vita-marvel-super-he… PlayStation Vita PlayStation Vita 9.0 9.0 Platformer 平台游戏 Y ÿ 2012 2012年 9 9 12 12
2 2 Great Splice: Tree of Life 拼接:生命之树 /games/splice/ipad-141070 / games / splice / ipad-141070 iPad 的iPad 8.5 8.5 Puzzle 难题 N ñ 2012 2012年 9 9 12 12
3 3 Great NHL 13 NHL 13 /games/nhl-13/xbox-360-128182 / games / nhl-13 / xbox-360-128182 Xbox 360 Xbox 360 8.5 8.5 Sports 体育 N ñ 2012 2012年 9 9 11 11
4 4 Great NHL 13 NHL 13 /games/nhl-13/ps3-128181 / games / nhl-13 / ps3-128181 PlayStation 3 的PlayStation 3 8.5 8.5 Sports 体育 N ñ 2012 2012年 9 9 11 11

在熊猫中使用标签建立索引 (Indexing Using Labels in Pandas)

Now that we know how to retrieve rows and columns by position, it’s worth looking into the other major way to work with DataFrames, which is to retrieve rows and columns by label.

既然我们知道如何按位置检索行和列,就值得研究使用DataFrames的另一种主要方法,即按标签检索行和列。

A major advantage of Pandas over NumPy is that each of the columns and rows has a label. Working with column positions is possible, but it can be hard to keep track of which number corresponds to which column.

与NumPy相比,Pandas的主要优势在于,每一列和每一行都有一个标签。 可以处理列的位置,但是很难跟踪哪个数字对应于哪个列。

We can work with labels using the method, which allows us to index using labels instead of positions.

我们可以使用方法处理标签,该方法允许我们使用标签而不是位置进行索引。

We can display the first five rows of reviews using the loc method like this:

我们可以使用loc方法显示reviews的前五行,如下所示:

reviewsreviews .. locloc [[ 00 :: 55 ,:],:]
score_phrase score_phrase title 标题 url 网址 platform 平台 score 得分 genre 类型 editors_choice editors_choice release_year release_year release_month release_month release_day release_day
0 0 Amazing 惊人 LittleBigPlanet PS Vita LittleBigPlanet PS Vita /games/littlebigplanet-vita/vita-98907 / games / littlebigplanet-vita / vita-98907 PlayStation Vita PlayStation Vita 9.0 9.0 Platformer 平台游戏 Y ÿ 2012 2012年 9 9 12 12
1 1个 Amazing 惊人 LittleBigPlanet PS Vita — Marvel Super Hero E… LittleBigPlanet PS Vita —惊奇超级英雄E… /games/littlebigplanet-ps-vita-marvel-super-he… / games / littlebigplanet-ps-vita-marvel-super-he… PlayStation Vita PlayStation Vita 9.0 9.0 Platformer 平台游戏 Y ÿ 2012 2012年 9 9 12 12
2 2 Great Splice: Tree of Life 拼接:生命之树 /games/splice/ipad-141070 / games / splice / ipad-141070 iPad 的iPad 8.5 8.5 Puzzle 难题 N ñ 2012 2012年 9 9 12 12
3 3 Great NHL 13 NHL 13 /games/nhl-13/xbox-360-128182 / games / nhl-13 / xbox-360-128182 Xbox 360 Xbox 360 8.5 8.5 Sports 体育 N ñ 2012 2012年 9 9 11 11
4 4 Great NHL 13 NHL 13 /games/nhl-13/ps3-128181 / games / nhl-13 / ps3-128181 PlayStation 3 的PlayStation 3 8.5 8.5 Sports 体育 N ñ 2012 2012年 9 9 11 11
5 5 Good Total War Battles: Shogun 全面战争:将军 /games/total-war-battles-shogun/mac-142565 / games /全面战争战斗将军/ mac-142565 Macintosh 苹果机 7.0 7.0 Strategy 战略 N ñ 2012 2012年 9 9 11 11

The above doesn’t actually look much different from reviews.iloc[0:5,:]. This is because while row labels can take on any values, our row labels match the positions exactly. You can see the row labels on the very left of the table above (they’re in bold). You can also see them by accessing the property of a DataFrame. We’ll display the row indexes for reviews:

上面的内容实际上与reviews.iloc[0:5,:]并没有太大区别。 这是因为尽管行标签可以采用任何值,但我们的行标签与位置完全匹配。 您可以在上方表格的最左侧看到行标签(它们以粗体显示)。 您还可以通过访问DataFrame的属性来查看它们。 我们将显示reviews的行索引:

Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, ...], dtype='int64')

Indexes don’t always have to match up with positions, though. In the below code cell, we’ll:

但是,索引不一定总是与位置匹配。 在下面的代码单元中,我们将:

  • Get row 10 to row 20 of reviews, and assign the result to some_reviews.
  • Display the first 5 rows of some_reviews.
  • 获取行10至行20reviews ,并分配结果some_reviews
  • 显示some_reviews的前5行。
some_reviews some_reviews = = reviewsreviews .. ilociloc [[ 1010 :: 2020 ,],]some_reviewssome_reviews .. headhead ()()
score_phrase score_phrase title 标题 url 网址 platform 平台 score 得分 genre 类型 editors_choice editors_choice release_year release_year release_month release_month release_day release_day
10 10 Good Tekken Tag Tournament 2 《铁拳》 Tag Tournament 2 /games/tekken-tag-tournament-2/ps3-124584 / games / tekken-tag-tournament-2 / ps3-124584 PlayStation 3 的PlayStation 3 7.5 7.5 Fighting 战斗 N ñ 2012 2012年 9 9 11 11
11 11 Good Tekken Tag Tournament 2 《铁拳》 Tag Tournament 2 /games/tekken-tag-tournament-2/xbox-360-124581 / games / tekken-tag-tournament-2 / xbox-360-124581 Xbox 360 Xbox 360 7.5 7.5 Fighting 战斗 N ñ 2012 2012年 9 9 11 11
12 12 Good Wild Blood 狂血 /games/wild-blood/iphone-139363 / games / wild-blood / iphone-139363 iPhone 苹果手机 7.0 7.0 NaN N N ñ 2012 2012年 9 9 10 10
13 13 Amazing 惊人 Mark of the Ninja 忍者印记 /games/mark-of-the-ninja-135615/xbox-360-129276 / games / mark-of-the-ninja-135615 / xbox-360-129276 Xbox 360 Xbox 360 9.0 9.0 Action, Adventure 动作,冒险 Y ÿ 2012 2012年 9 9 7 7
14 14 Amazing 惊人 Mark of the Ninja 忍者印记 /games/mark-of-the-ninja-135615/pc-143761 / games / mark-of-the-ninja-135615 / pc-143761 PC 个人电脑 9.0 9.0 Action, Adventure 动作,冒险 Y ÿ 2012 2012年 9 9 7 7

As you can see above, in some_reviews, the row indexes start at 10 and end at 20. Thus, trying loc along with numbers lower than 10 or higher than 20 will result in an error:

如上所示,在some_reviews ,行索引从10开始,在20结束。 因此,将loc与小于10或大于20数字一起尝试将导致错误:

------------------------------------------------------------------------------------------------------------------------------------------------------KeyError                                  Traceback (most recent call last)KeyError                                  Traceback (most recent call last)
in
in
()()----> 1----> 1 some_reviews some_reviews .loc. loc [[ 99 :: 2121 ,, :: ]]/Users/vik/python_envs/dsserver/lib/python3.4/site-packages/pandas/core/indexing.py in /Users/vik/python_envs/dsserver/lib/python3.4/site-packages/pandas/core/indexing.py in __getitem____getitem__ (self, key)(self, key) 1198 1198 def __getitem__def __getitem__ (self( self , key, key )) :: 1199 1199 if typeif type (key( key ) ) is tupleis tuple ::-> 1200-> 1200 return selfreturn self ._getitem_tuple. _getitem_tuple (key( key )) 1201 1201 elseelse :: 1202 1202 return selfreturn self ._getitem_axis. _getitem_axis (key( key , axis, axis == 00 ))/Users/vik/python_envs/dsserver/lib/python3.4/site-packages/pandas/core/indexing.py in /Users/vik/python_envs/dsserver/lib/python3.4/site-packages/pandas/core/indexing.py in _getitem_tuple_getitem_tuple (self, tup)(self, tup) 702 702 703 703 # no multi-index, so validate all of the indexers# no multi-index, so validate all of the indexers--> 704--> 704 self self ._has_valid_tuple. _has_valid_tuple (tup( tup )) 705 705 706 706 # ugly hack for GH #836# ugly hack for GH #836/Users/vik/python_envs/dsserver/lib/python3.4/site-packages/pandas/core/indexing.py in /Users/vik/python_envs/dsserver/lib/python3.4/site-packages/pandas/core/indexing.py in _has_valid_tuple_has_valid_tuple (self, key)(self, key) 129 129 if i if i >= self>= self .obj. obj .ndim. ndim :: 130 130 raise IndexingErrorraise IndexingError (( 'Too many indexers''Too many indexers' ))--> 131--> 131 if if not selfnot self ._has_valid_type. _has_valid_type (k( k , i, i )) :: 132 raise ValueError("Location based indexing can only have [%s] " 132 raise ValueError("Location based indexing can only have [%s] " 133 "types" % self._valid_types) 133 "types" % self._valid_types)/Users/vik/python_envs/dsserver/lib/python3.4/site-packages/pandas/core/indexing.py in /Users/vik/python_envs/dsserver/lib/python3.4/site-packages/pandas/core/indexing.py in _has_valid_type_has_valid_type (self, key, axis)(self, key, axis) 1258 raise KeyError( 1258 raise KeyError( 1259 1259 "start bound [%s] is not the [%s]" "start bound [%s] is not the [%s]" %%-> 1260-> 1260 (key( key .start. start , self, self .obj. obj ._get_axis_name. _get_axis_name (axis( axis )) )) 1261 ) 1261 ) 1262 1262 if keyif key .stop . stop is is not not NoneNone ::KeyError: 'start bound [9] is not the [index]'KeyError : 'start bound [9] is not the [index]'

As we mentioned earlier, column labels can make life much easier when you’re working with data. We can specify column labels in the loc method to retrieve columns by label instead of by position.

如前所述,在使用数据时,列标签可以使工作更加轻松。 我们可以在loc方法中指定列标签,以按标签而不是按位置检索列。

0    9.01    9.02    8.53    8.54    8.55    7.0Name: score, dtype: float64

We can also specify more than one column at a time by passing in a list:

我们还可以通过传递列表来一次指定多个列:

reviewsreviews .. locloc [:[: 55 ,[,[ "score""score" , , "release_year""release_year" ]]]]
score 得分 release_year release_year
0 0 9.0 9.0 2012 2012年
1 1个 9.0 9.0 2012 2012年
2 2 8.5 8.5 2012 2012年
3 3 8.5 8.5 2012 2012年
4 4 8.5 8.5 2012 2012年
5 5 7.0 7.0 2012 2012年

熊猫系列物件 (Pandas Series Objects)

We can retrieve an individual column in Pandas a few different ways. So far, we’ve seen two types of syntax for this:

我们可以通过几种不同的方式在Pandas中检索单个列。 到目前为止,我们已经看到了两种语法:

  • reviews.iloc[:,1] – will retrieve the second column.
  • reviews.loc[:,"score_phrase"] – will also retrieve the second column.
  • reviews.iloc[:,1] –将检索第二列。
  • reviews.loc[:,"score_phrase"] –还将检索第二列。

There’s a third, even easier, way to retrieve a whole column. We can just specify the column name in square brackets, like with a dictionary:

还有第三种甚至更简单的方法来检索整列。 我们可以在方括号中指定列名称,例如使用字典:

0     9.01     9.02     8.53     8.54     8.55     7.06     3.07     9.08     3.09     7.010    7.511    7.512    7.013    9.014    9.0...18610     6.018611     5.818612     7.818613     8.018614     9.218615     9.218616     7.518617     8.418618     9.118619     7.918620     7.618621     9.018622     5.818623    10.018624    10.0Name: score, Length: 18625, dtype: float64

We can also use lists of columns with this method:

我们还可以通过以下方法使用列列表:

reviewsreviews [[[[ "score""score" , , "release_year""release_year" ]]]]
score 得分 release_year release_year
0 0 9.0 9.0 2012 2012年
1 1个 9.0 9.0 2012 2012年
2 2 8.5 8.5 2012 2012年
3 3 8.5 8.5 2012 2012年
4 4 8.5 8.5 2012 2012年
5 5 7.0 7.0 2012 2012年
6 6 3.0 3.0 2012 2012年
7 7 9.0 9.0 2012 2012年
8 8 3.0 3.0 2012 2012年
9 9 7.0 7.0 2012 2012年
10 10 7.5 7.5 2012 2012年
11 11 7.5 7.5 2012 2012年
12 12 7.0 7.0 2012 2012年
13 13 9.0 9.0 2012 2012年
14 14 9.0 9.0 2012 2012年
15 15 6.5 6.5 2012 2012年
16 16 6.5 6.5 2012 2012年
17 17 8.0 8.0 2012 2012年
18 18 5.5 5.5 2012 2012年
19 19 7.0 7.0 2012 2012年
20 20 7.0 7.0 2012 2012年
21 21 7.5 7.5 2012 2012年
22 22 7.5 7.5 2012 2012年
23 23 7.5 7.5 2012 2012年
24 24 9.0 9.0 2012 2012年
25 25 7.0 7.0 2012 2012年
26 26 9.0 9.0 2012 2012年
27 27 7.5 7.5 2012 2012年
28 28 8.0 8.0 2012 2012年
29 29 6.5 6.5 2012 2012年
18595 18595 4.4 4.4 2016 2016年
18596 18596 6.5 6.5 2016 2016年
18597 18597 4.9 4.9 2016 2016年
18598 18598 6.8 6.8 2016 2016年
18599 18599 7.0 7.0 2016 2016年
18600 18600 7.4 7.4 2016 2016年
18601 18601 7.4 7.4 2016 2016年
18602 18602 7.4 7.4 2016 2016年
18603 18603 7.8 7.8 2016 2016年
18604 18604 8.6 8.6 2016 2016年
18605 18605 6.0 6.0 2016 2016年
18606 18606 6.4 6.4 2016 2016年
18607 18607 7.0 7.0 2016 2016年
18608 18608 5.4 5.4 2016 2016年
18609 18609 8.0 8.0 2016 2016年
18610 18610 6.0 6.0 2016 2016年
18611 18611 5.8 5.8 2016 2016年
18612 18612 7.8 7.8 2016 2016年
18613 18613 8.0 8.0 2016 2016年
18614 18614 9.2 9.2 2016 2016年
18615 18615 9.2 9.2 2016 2016年
18616 18616 7.5 7.5 2016 2016年
18617 18617 8.4 8.4 2016 2016年
18618 18618 9.1 9.1 2016 2016年
18619 18619 7.9 7.9 2016 2016年
18620 18620 7.6 7.6 2016 2016年
18621 18621 9.0 9.0 2016 2016年
18622 18622 5.8 5.8 2016 2016年
18623 18623 10.0 10.0 2016 2016年
18624 18624 10.0 10.0 2016 2016年

18625 rows × 2 columns

18625行×2列

When we retrieve a single column, we’re actually retrieving a Pandas object. A DataFrame stores tabular data, but a Series stores a single column or row of data.

当我们检索单个列时,实际上是在检索Pandas 对象。 DataFrame存储表格数据,而Series存储数据的单列或单行。

We can verify that a single column is a Series:

我们可以验证单个列是否为系列:

pandas.core.series.Series

We can create a Series manually to better understand how it works. To create a Series, we pass a list or NumPy array into the Series object when we instantiate it:

我们可以手动创建系列以更好地了解其工作原理。 要创建一个Series,我们在实例化它时将一个列表或NumPy数组传递给Series对象:

s1 s1 = = pdpd .. SeriesSeries ([([ 11 ,, 22 ])])s1s1
0    11    2dtype: int64

A Series can contain any type of data, including mixed types. Here, we create a Series that contains string objects:

系列可以包含任何类型的数据,包括混合类型。 在这里,我们创建一个包含字符串对象的系列:

0        Boris Yeltsin1    Mikhail Gorbachevdtype: object

在熊猫中创建一个DataFrame (Creating A DataFrame in Pandas)

We can create a DataFrame by passing multiple Series into the DataFrame class. Here, we pass in the two Series objects we just created, s1 as the first row, and s2 as the second row:

我们可以通过将多个Series传递到DataFrame类中来创建DataFrame。 在这里,我们传入我们刚刚创建的两个Series对象, s1作为第一行, s2作为第二行:

pdpd .. DataFrameDataFrame ([([ s1s1 ,, s2s2 ])])
0 0 1 1个
0 0 1 1个 2 2
1 1个 Boris Yeltsin 鲍里斯·叶利钦 Mikhail Gorbachev 米哈伊尔·戈尔巴乔夫

We can also accomplish the same thing with a list of lists. Each inner list is treated as a row in the resulting DataFrame:

我们还可以使用列表列表完成同样的事情。 每个内部列表在结果DataFrame中被视为一行:

0 0 1 1个
0 0 1 1个 2 2
1 1个 Boris Yeltsin 鲍里斯·叶利钦 Mikhail Gorbachev 米哈伊尔·戈尔巴乔夫

We can specify the column labels when we create a DataFrame:

我们可以在创建DataFrame时指定列标签:

pdpd .. DataFrameDataFrame (    (    [        [        [[ 11 ,, 22 ],        ],        [[ "Boris Yeltsin""Boris Yeltsin" , , "Mikhail Gorbachev""Mikhail Gorbachev" ]    ]    ],    ],    columnscolumns == [[ "column1""column1" , , "column2""column2" ]]))
column1 第1栏 column2 专栏2
0 0 1 1个 2 2
1 1个 Boris Yeltsin 鲍里斯·叶利钦 Mikhail Gorbachev 米哈伊尔·戈尔巴乔夫

As well as the row labels (the index):

以及行标签(索引):

column1 第1栏 column2 专栏2
row1 第1行 1 1个 2 2
row2 第2行 Boris Yeltsin 鲍里斯·叶利钦 Mikhail Gorbachev 米哈伊尔·戈尔巴乔夫

We’re then able index the DataFrame using the labels:

然后,我们可以使用标签为DataFrame编制索引:

frameframe .. locloc [[ "row1""row1" :: "row2""row2" , , "column1""column1" ]]
row1                1row2    Boris YeltsinName: column1, dtype: object

We can skip specifying the columns keyword argument if we pass a dictionary into the DataFrame constructor. This will automatically setup column names:

如果将字典传递给DataFrame构造函数,则可以跳过指定columns关键字参数的DataFrame 。 这将自动设置列名称:

column1 第1栏 column2 专栏2
0 0 1 1个 2 2
1 1个 Boris Yeltsin 鲍里斯·叶利钦 Mikhail Gorbachev 米哈伊尔·戈尔巴乔夫

熊猫DataFrame方法 (Pandas DataFrame Methods)

As we mentioned earlier, each column in a DataFrame is a Series object:

如前所述,DataFrame中的每一列都是一个Series对象:

typetype (( reviewsreviews [[ "title""title" ])])
pandas.core.series.Series

We can call most of the same methods on a Series object that we can on a DataFrame, including head:

我们可以在Series对象上调用与在DataFrame上可以调用的大多数相同方法,包括head

0                              LittleBigPlanet PS Vita1    LittleBigPlanet PS Vita -- Marvel Super Hero E...2                                 Splice: Tree of Life3                                               NHL 134                                               NHL 13Name: title, dtype: object

Pandas Series and DataFrames also have other methods that make calculations simpler. For example, we can use the method to find the mean of a Series:

Pandas Series和DataFrames还具有其他使计算更简单的方法。 例如,我们可以使用方法来查找Series的均值:

reviewsreviews [[ "score""score" ]] .. meanmean ()()
6.950459060402685

We can also call the similar method, which will find the mean of each numerical column in a DataFrame by default:

我们还可以调用类似的方法,该方法默认情况下将查找中每个数字列的平均值:

score               6.950459release_year     2006.515329release_month       7.138470release_day        15.603866dtype: float64

We can modify the axis keyword argument to mean in order to compute the mean of each row or of each column. By default, axis is equal to 0, and will compute the mean of each column. We can also set it to 1 to compute the mean of each row. Note that this will only compute the mean of the numerical values in each row:

我们可以将axis关键字参数修改为mean ,以便计算每一行或每一列的平均值。 默认情况下, axis等于0 ,并将计算每列的平均值。 我们还可以将其设置为1以计算每行的平均值。 请注意,这只会计算每行中数值的平均值:

reviewsreviews .. meanmean (( axisaxis == 11 ))
0     510.5001     510.5002     510.3753     510.1254     510.1255     509.7506     508.7507     510.2508     508.7509     509.75010    509.87511    509.87512    509.50013    509.25014    509.250...18610    510.25018611    508.70018612    509.20018613    508.00018614    515.05018615    515.05018616    508.37518617    508.60018618    515.02518619    514.72518620    514.65018621    515.00018622    513.95018623    515.00018624    515.000Length: 18625, dtype: float64

There are quite a few methods on Series and DataFrames that behave like mean. Here are some handy ones:

Series和DataFrame上有很多方法的行为类似于mean 。 这里有一些方便的东西:

We can use the corr method to see if any columns correlation with score. For instance, this would tell us if games released more recently have been getting higher reviews (release_year), or if games released towards the end of the year score better (release_month):

我们可以使用corr方法查看是否有任何列与score相关。 例如,这可以告诉我们最近发布的游戏获得了更高的评价( release_year ),还是在年底之前发布的游戏获得了更好的评分( release_month ):

score 得分 release_year release_year release_month release_month release_day release_day
score 得分 1.000000 1.000000 0.062716 0.062716 0.007632 0.007632 0.020079 0.020079
release_year release_year 0.062716 0.062716 1.000000 1.000000 -0.115515 -0.115515 0.016867 0.016867
release_month release_month 0.007632 0.007632 -0.115515 -0.115515 1.000000 1.000000 -0.067964 -0.067964
release_day release_day 0.020079 0.020079 0.016867 0.016867 -0.067964 -0.067964 1.000000 1.000000

As you can see above, none of our numeric columns correlates with score, meaning that release timing doesn’t linearly relate to review score.

正如您在上面看到的那样,我们的所有数字列都没有与score相关,这意味着发布时间与评论得分没有线性关系。

DataFrame Math与Pandas (DataFrame Math with Pandas)

We can also perform math operations on Series or DataFrame objects. For example, we can divide every value in the score column by 2 to switch the scale from 010 to 05:

我们还可以对Series或DataFrame对象执行数学运算。 例如,我们可以将score列中的每个值除以2以将标度从010切换到05

reviewsreviews [[ "score""score" ] ] / / 22
0     4.501     4.502     4.253     4.254     4.255     3.506     1.507     4.508     1.509     3.5010    3.7511    3.7512    3.5013    4.5014    4.50...18610    3.0018611    2.9018612    3.9018613    4.0018614    4.6018615    4.6018616    3.7518617    4.2018618    4.5518619    3.9518620    3.8018621    4.5018622    2.9018623    5.0018624    5.00Name: score, Length: 18625, dtype: float64

All the common mathematical operators that work in Python, like +, -, *, /, and ^ will work, and will apply to each element in a DataFrame or a Series.

所有在Python中运行的常用数学运算符,例如+-*/^都可以使用,并将应用于DataFrame或Series中的每个元素。

熊猫中的布尔索引 (Boolean Indexing in Pandas)

As we saw above, the mean of all the values in the score column of reviews is around 7. What if we wanted to find all the games that got an above average score? We could start by doing a comparison. The comparison compares each value in a Series to a specified value, then generate a Series full of Boolean values indicating the status of the comparison. For example, we can see which of the rows have a score value higher than 7:

正如我们在上面看到的, reviewsscore栏中所有值的平均值约为7 。 如果我们想找到所有得分都高于平均水平的游戏怎么办? 我们可以先进行比较。 比较会将“系列”中的每个值与指定值进行比较,然后生成一个“系列”,其中包含表示比较状态的布尔值。 例如,我们可以看到哪些行的score值高于7

0      True1      True2      True3      True4      True5     False6     False7      True8     False9     False10     True11     True12    False13     True14     True...18610    False18611    False18612     True18613     True18614     True18615     True18616     True18617     True18618     True18619     True18620     True18621     True18622    False18623     True18624     TrueName: score, Length: 18625, dtype: bool

Once we have a Boolean Series, we can use it to select only rows in a DataFrame where the Series contains the value True. So, we could only select rows in reviews where score is greater than 7:

一旦有了Boolean Series,我们就可以使用它来选择DataFrame中Series包含值True 。 因此,我们只能在score大于7 reviews中选择行:

filtered_reviews filtered_reviews = = reviewsreviews [[ score_filterscore_filter ]]filtered_reviewsfiltered_reviews .. headhead ()()
score_phrase score_phrase title 标题 url 网址 platform 平台 score 得分 genre 类型 editors_choice editors_choice release_year release_year release_month release_month release_day release_day
0 0 Amazing 惊人 LittleBigPlanet PS Vita LittleBigPlanet PS Vita /games/littlebigplanet-vita/vita-98907 / games / littlebigplanet-vita / vita-98907 PlayStation Vita PlayStation Vita 9.0 9.0 Platformer 平台游戏 Y ÿ 2012 2012年 9 9 12 12
1 1个 Amazing 惊人 LittleBigPlanet PS Vita — Marvel Super Hero E… LittleBigPlanet PS Vita —惊奇超级英雄E… /games/littlebigplanet-ps-vita-marvel-super-he… / games / littlebigplanet-ps-vita-marvel-super-he… PlayStation Vita PlayStation Vita 9.0 9.0 Platformer 平台游戏 Y ÿ 2012 2012年 9 9 12 12
2 2 Great Splice: Tree of Life 拼接:生命之树 /games/splice/ipad-141070 / games / splice / ipad-141070 iPad 的iPad 8.5 8.5 Puzzle 难题 N ñ 2012 2012年 9 9 12 12
3 3 Great NHL 13 NHL 13 /games/nhl-13/xbox-360-128182 / games / nhl-13 / xbox-360-128182 Xbox 360 Xbox 360 8.5 8.5 Sports 体育 N ñ 2012 2012年 9 9 11 11
4 4 Great NHL 13 NHL 13 /games/nhl-13/ps3-128181 / games / nhl-13 / ps3-128181 PlayStation 3 的PlayStation 3 8.5 8.5 Sports 体育 N ñ 2012 2012年 9 9 11 11

It’s possible to use multiple conditions for filtering. Let’s say we want to find games released for the Xbox One that have a score of more than 7. In the below code, we:

可以使用多个条件进行过滤。 假设我们要查找为Xbox One发行的得分超过7 。 在下面的代码中,我们:

  • Setup a filter with two conditions:
    • Check if score is greater than 7.
    • Check if platform equals Xbox One
  • Apply the filter to reviews to get only the rows we want.
  • Use the head method to print the first 5 rows of filtered_reviews.
  • 设置具有两个条件的过滤器:
    • 检查score是否大于7
    • 检查platform等于Xbox One
  • 将过滤器应用于reviews以仅获取所需的行。
  • 使用head方法打印前5filtered_reviews
score_phrase score_phrase title 标题 url 网址 platform 平台 score 得分 genre 类型 editors_choice editors_choice release_year release_year release_month release_month release_day release_day
17137 17137 Amazing 惊人 Gone Home 回家了 /games/gone-home/xbox-one-20014361 / games / gone-home / xbox-one-20014361 Xbox One Xbox One 9.5 9.5 Simulation 模拟 Y ÿ 2013 2013年 8 8 15 15
17197 17197 Amazing 惊人 Rayman Legends 雷曼传奇 /games/rayman-legends/xbox-one-20008449 / games / rayman-legends / xbox-one-20008449 Xbox One Xbox One 9.5 9.5 Platformer 平台游戏 Y ÿ 2013 2013年 8 8 26 26
17295 17295 Amazing 惊人 LEGO Marvel Super Heroes 乐高漫威超级英雄 /games/lego-marvel-super-heroes/xbox-one-20000826 / games / lego-marvel-super-heroes / xbox-one-20000826 Xbox One Xbox One 9.0 9.0 Action 行动 Y ÿ 2013 2013年 10 10 22 22
17313 17313 Great Dead Rising 3 死亡崛起3 /games/dead-rising-3/xbox-one-124306 / games / dead-rising-3 / xbox-one-124306 Xbox One Xbox One 8.3 8.3 Action 行动 N ñ 2013 2013年 11 11 18 18
17317 17317 Great Killer Instinct 杀手本能 /games/killer-instinct-2013/xbox-one-20000538 / games / killer-instinct-2013 / xbox-one-20000538 Xbox One Xbox One 8.4 8.4 Fighting 战斗 N ñ 2013 2013年 11 11 18 18

When filtering with multiple conditions, it’s important to put each condition in parentheses, and separate them with a single ampersand (&).

当与多个条件滤波,它把每个条件括号,并将它们与一个单一的符号(分离是很重要的& )。

熊猫图 (Pandas Plotting)

Now that we know how to filter, we can create plots to observe the review distribution for the Xbox One vs the review distribution for the PlayStation 4. This will help us figure out which console has better games. We can do this via a histogram, which will plot the frequencies for different score ranges. This will tell us which console has more highly reviewed games.

现在我们知道如何过滤,我们可以创建图来观察Xbox One的评论分布与PlayStation 4的评论分布。 这将帮助我们确定哪个控制台具有更好的游戏。 我们可以通过直方图来做到这一点,直方图将绘制不同分数范围的频率。 这将告诉我们哪个控制台具有更受好评的游戏。

We can make a histogram for each console using the method. This method utilizes matplotlib, the popular Python plotting library, under the hood to generate good-looking plots.

我们可以使用方法为每个控制台制作一个直方图。 该方法利用内部流行的Python绘图库matplotlib生成美观的绘图。

The plot method defaults to drawing a line graph. We’ll need to pass in the keyword argument kind="hist" to draw a histogram instead.

plot方法默认为绘制折线图。 我们需要传入关键字参数kind="hist"来绘制直方图。

In the below code, we:

在下面的代码中,我们:

  • Call %matplotlib inline to setup plotting inside a Jupyter notebook.
  • Filter reviews to only have data about the Xbox One.
  • Plot the score column.
  • %matplotlib inline调用%matplotlib inline以在Jupyter笔记本中设置打印。
  • 筛选reviews以仅包含有关Xbox One数据。
  • 绘制score列。
%% matplotlib inlinematplotlib inlinereviewsreviews [[ reviewsreviews [[ "platform""platform" ] ] == == "Xbox One""Xbox One" ][][ "score""score" ]] .. plotplot (( kindkind == "hist""hist" ))

We can also do the same for the PS4:

我们也可以对PS4做同样的事情:

It appears from our histogram that the PlayStation 4 has many more highly rated games than the Xbox One.

从我们的直方图中可以看出, PlayStation 4Xbox One具有更高的评价。

filtered_reviewsfiltered_reviews [[ "score""score" ]] .. histhist ()()

进一步阅读 (Further Reading)

翻译自:

转载地址:http://jhqwd.baihongyu.com/

你可能感兴趣的文章
idea常用设置汇总
查看>>
Node.SelectNodes
查看>>
winform 指定浏览器打开链接
查看>>
[Leetcode] Subset II
查看>>
Lambda表达式语法进一步巩固
查看>>
Vue基础安装(精华)
查看>>
Git 提交修改内容和查看被修改的内容
查看>>
PAT - 1008. 数组元素循环右移问题 (20)
查看>>
请求出现 Nginx 413 Request Entity Too Large错误的解决方法
查看>>
配置php_memcache访问网站的步骤
查看>>
textarea 输入框限制字数
查看>>
基本硬件知识(一)
查看>>
js之事件冒泡和事件捕获
查看>>
Linux——LVM 逻辑卷的创建与扩展
查看>>
WIN2003 Apache httpd.exe 进程内存只增不减
查看>>
用Java设计简易的计算器
查看>>
通讯框架后续完善3
查看>>
SharedPreference工具类
查看>>
css文本样式-css学习之旅(4)
查看>>
Java多线程3:Thread中的静态方法
查看>>