pandas 這麼可愛,我爭取多用幾張很萌很萌的照片,哈哈哈

好的,上一篇文章做了pandas中非常基礎的一些練習題,從這篇文章開始,可能會慢慢複雜起來,當然這個也是學習的一個比較科學的方式。

這個系列的練習題是Github上面的,地址在這

guipsamora/pandas_exercises?

github.com
圖標

好的今天接著上篇文章的Filtering and Sorting Data

Ex2 - Filtering and Sorting Data

This time we are going to pull data directly from the internet.
Step 1. Import the necessary libraries

#前面幾題都是很基礎的做法
import pandas as pd
import numpy as np

Step 2. Import the dataset from this address.

euro12 = pd.read_csv(https://raw.githubusercontent.com/jokecamp/FootballData/master/UEFA_European_Championship/Euro%202012/Euro%202012%20stats%20TEAM.csv)

Step 3. Assign it to a variable called euro12.
euro12.head()

Step 4. Select only the Goal column.

euro12.Goals

Step 5. How many team participated in the Euro2012?

euro12.Team.sort_values().count()

Step 6. What is the number of columns in the dataset?
euro12.shape[1]

Step 7. View only the columns Team, Yellow Cards and Red Cards and assign them to a dataframe called discipline

discipline = euro12[[Team,Yellow Cards,Red Cards]]
discipline

Step 8. Sort the teams by Red Cards, then to Yellow Cards

discipline.sort_values([Yellow Cards,Yellow Cards],ascending=False)
#output

Team Yellow Cards Red Cards
7 Italy 16 0
10 Portugal 12 0
13 Spain 11 0
0 Croatia 9 0
6 Greece 9 1
1 Czech Republic 7 0
9 Poland 7 1
14 Sweden 7 0
4 France 6 0
11 Republic of Ireland 6 1
12 Russia 6 0
3 England 5 0
8 Netherlands 5 0
15 Ukraine 5 0
2 Denmark 4 0
5 Germany 4 0

Step 9. Calculate the mean Yellow Cards given per Team

discipline[Yellow Cards].mean()

Step 10. Filter teams that scored more than 6 goals

euro12[euro12.Goals>6]

Step 11. Select the teams that start with G

euro12[euro12.Team.str.startswith(G)]

Step 12. Select the first 7 columns

#找到前7列的數據
#用切片iloc
euro12.iloc[:,0:7]

Step 13. Select all columns except the last 3.
#同樣使用iloc來對列進行切片操作
#題目要求,不包含最後三列,那麼可以使用從0開始到倒數三列的切片模式
euro12.iloc[:,:-3]

Step 14. Present only the Shooting Accuracy from England, Italy and Russia

#前面兩題都是iloc,即對列進行切盼操作,這一題是使用loc對行進行切片操作
#題目還要求必須是英格蘭,義大利和俄羅斯這三個國家,所以考慮使用isin函數來進行判斷
euro12.loc[euro12.Team.isin([England, Italy, Russia]), [Team,Shooting Accuracy]]

小結:這一part的主要考到了iloc和loc這裡兩個點,其中還夾雜了一些isin和判斷。

那麼這裡我們來回顧一下loc(軸標籤),因為iloc(整數標籤),軸標籤對於DataFrame來講更方便使用所以這裡就主要回顧一下loc了

利用python進行數據分析這本書裡面有對loc和iloc進行一個比較詳細的介紹,我這裡做一個表格,詳細的描述一下

我們來看一下jupyter notebook 裡面出現的例子,這裡使用了shift+tab,然後摁四次,就可以得到內置的代碼解釋

df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
... index=[cobra, viper, sidewinder],
... columns=[max_speed, shield])
df

輸出結果

df.loc[viper] #只需要viper這一行的數據
max_speed 4
shield 5
Name: viper, dtype: int64
#List of labels. Note using ``[[]]`` returns a DataFrame.
#能夠看到這個實際輸出是一個Series,而不是一個DataFrame

#那麼想得到一個DataFrame,需要怎麼做的呢
df.loc[[viper]] #這個就可以得到一個DataFrame

下一個是切分兩行的數據

df.loc[[viper, sidewinder]]
max_speed shield
viper 4 5
sidewinder 7 8

Single label for row and column

切分出單個 數據,需要的是行和列的坐標來確定,如下述例子

df.loc[cobra, shield]
2

Slice with labels for row and single label for column. As mentioned
above, note that both the start and stop of the slice are included.

那麼同樣也可以使用多個值,然後利用切片的方式,如下

df.loc[cobra:viper, max_speed]
cobra 1
viper 4
Name: max_speed, dtype: int64

Boolean list with the same length as the row axis

使用布爾型數據

df.loc[[False, False, True]]
max_speed shield
sidewinder 7 8

Conditional that returns a boolean Series
#這一條語句基本就可以理解loc的使用形式了,也就是說,loc是對行進行切分,可以通過布爾的形式,對某些列進行設置

加入條件進行判斷

df.loc[df[shield] > 6]
#剛好今天的練習題目裡面也有,就是可以直行判斷,然後判斷以後的數據行顯示出來
max_speed shield
sidewinder 7 8

Conditional that returns a boolean Series with column labels specified

加入列元素,定位切分得到一條數據

df.loc[df[shield] > 6, [max_speed]]
max_speed
sidewinder 7

Callable that returns a boolean Series

在loc裡面應用函數

df.loc[lambda df: df[shield] == 8]
#這條語句等價於
df.loc[ df[shield] == 8]
#這裡使用lambda,是為了說明,可以直接嵌套匿名函數的來得到想要的數據的
max_speed shield
sidewinder 7 8

**Setting values**

Set value for all items matching the list of labels

為目標數據定值,比如下面的例子

df.loc[[viper, sidewinder], [shield]] = 50
df
max_speed shield
cobra 1 2
viper 4 50
sidewinder 7 50

Set value for an entire row

同樣為某一行數據進行賦值

df.loc[cobra] = 10
df
max_speed shield
cobra 10 10
viper 4 50
sidewinder 7 50

Set value for an entire column

如果,想直接對某一列進行操作,就需要使用df.loc[:,"column"]的形式了,如下

df.loc[:, max_speed] = 30
#這裡就是使用了取出說有行的形式,然後給max_speed單獨賦值的方式
df
max_speed shield
cobra 30 10
viper 30 50
sidewinder 30 50

Set value for rows matching callable condition

同樣的對於滿足條件的數據,進行賦值,其實這裡也就是多了最後的賦值的一步,前面的都是一樣的,先去找到目標數據,然後在賦值

df.loc[df[shield] > 35] = 0
#為shield>35的數據切片全部賦值為零
df
max_speed shield
cobra 30 10
viper 0 0
sidewinder 0 0

**Getting values on a DataFrame with an index that has integer labels**

#使用整數型數據,作為索引

Another example using integers for the index

df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
... index=[7, 8, 9], columns=[max_speed, shield])
df
max_speed shield
7 1 2
8 4 5
9 7 8

Slice with integer labels for rows. As mentioned above, note that both
the start and stop of the slice are included.

#按照索引來切片
df.loc[7:9]
max_speed shield
7 1 2
8 4 5
9 7 8

使用多重索引時的操作

首先創建一個擁有多重索引的DataFrame,這裡就是外層索引分為cobra,sidewinder,viper然後內部還有索引

**Getting values with a MultiIndex**

A number of examples using a DataFrame with a MultiIndex

tuples = [
... (cobra, mark i), (cobra, mark ii),
... (sidewinder, mark i), (sidewinder, mark ii),
... (viper, mark ii), (viper, mark iii)
... ]
index = pd.MultiIndex.from_tuples(tuples)
values = [[12, 2], [0, 4], [10, 20],
... [1, 4], [7, 1], [16, 36]]
df = pd.DataFrame(values, columns=[max_speed, shield], index=index)
df
max_speed shield
cobra mark i 12 2
mark ii 0 4
sidewinder mark i 10 20
mark ii 1 4
viper mark ii 7 1
mark iii 16 36

Single label. Note this returns a DataFrame with a single index.

#想要獲得cobra的所有數據

df.loc[cobra]
max_speed shield
mark i 12 2
mark ii 0 4

Single index tuple. Note this returns a Series.

那麼如果想要獲得單個的數據要怎麼處理呢?

df.loc[(cobra, mark ii)]
max_speed 0
shield 4
Name: (cobra, mark ii), dtype: int64

Single label for row and column. Similar to passing in a tuple, this
returns a Series.

#需要注意的是這裡返回的是一個Series數據,如果想返回一個DataFrame,就要使用[[]]
df.loc[cobra, mark i]
max_speed 12
shield 2
Name: (cobra, mark i), dtype: int64

Single tuple. Note using ``[[]]`` returns a DataFrame.

#這裡就是使用了[[]]然後的得到的是一個DataFrame型數據
df.loc[[(cobra, mark ii)]]
max_speed shield
cobra mark ii 0 4

Single tuple for the index with a single label for the column

輸出結果如下

那上面的數據都是切出了一行的數據,我想要得到,某一個單獨的數據,要怎麼操作呢?

此時就要,在新加一個列的數據,來進行切分

df.loc[(cobra, mark i), shield]
2

Slice from index tuple to single label
#其實這裡也不難理解,因為有多重索引時,首先需要找到最內層的索引

#如果我想查詢多行索引對應的數據,要怎麼處理呢?可以使用:的形式

如下所示

df.loc[(cobra, mark i):viper]
max_speed shield
cobra mark i 12 2
mark ii 0 4
sidewinder mark i 10 20
mark ii 1 4
viper mark ii 7 1
mark iii 16 36

Slice from index tuple to index tuple

那如果我想對多行數據進行一個條件設置,要怎麼操作呢?

比如需要從cobra的第一條數據到viper的第一條數據,也就同樣需要用到:

其實這裡的邏輯都是一樣的,只不過在具體實現的時候可能稍微多了一些

比如下面的例子

df.loc[(cobra, mark i):(viper, mark ii)]
max_speed shield
cobra mark i 12 2
mark ii 0 4
sidewinder mark i 10 20
mark ii 1 4
viper mark ii 7 1

同樣的,我只想的得到shield這一列的內容,那麼我只需要在上面的語句的基礎上加一個特定的列就好

df.loc[(cobra, mark i):(viper, mark ii),shield]
#output

cobra mark i 2
mark ii 4
sidewinder mark i 20
mark ii 4
viper mark ii 1
Name: shield, dtype: int64
#注意這裡是Series型

好的,到這裡基本就把loc重新複習了一遍,下面我們繼續下一個part的練習,但是考慮到篇幅的原因,我這裡就暫且打住,重新寫一篇

如果你覺得這篇文章還不錯,希望能給我一個贊,雖然我寫這個專欄的目的是希望自己能夠通過寫專欄的形式,倒逼自己去每天學習,但是你們的一個贊將給與我莫大的支持。謝謝!

推薦閱讀:

相关文章