1. 程式人生 > >第3章 Pandas資料處理(3.9-3.10)_Python資料科學手冊學習筆記

第3章 Pandas資料處理(3.9-3.10)_Python資料科學手冊學習筆記

3.9 累計與分組

3.9.1 行星資料

import seaborn as sns
planets = sns.load_dataset('planets')
planets.shape
(1035, 6)
planets.head()
method number orbital_period mass distance year
0 Radial Velocity 1 269.300 7.10 77.40 2006
1 Radial Velocity 1 874.774 2.21 56.95 2008
2 Radial Velocity 1 763.000 2.60 19.84 2011
3 Radial Velocity 1 326.030 19.40 110.62 2007
4 Radial Velocity 1 516.220 10.50 119.47 2009

資料包括截止2014年已被發現的一千多顆外行星的資料.

3.9.2 Pandas的簡單累計功能

import numpy as np
import pandas as pd
rng = np.random.RandomState(42)
ser = pd.Series(rng.rand(5))
ser
0    0.374540
1    0.950714
2    0.731994
3    0.598658
4    0.156019
dtype: float64
ser.sum()
2.811925491708157
ser.mean()
0.5623850983416314

DataFrame的累計函式預設對列進行統計

df = pd.DataFrame({'a':rng.rand(5),
                  'b':rng.rand(5)})
df
a b
0 0.155995 0.020584
1 0.058084 0.969910
2 0.866176 0.832443
3 0.601115 0.212339
4 0.708073 0.181825
df.mean()
a    0.477888
b    0.443420
dtype: float64

設定axis引數, 可以對每一行進行統計

df.mean(axis='columns')
0    0.088290
1    0.513997
2    0.849309
3    0.406727
4    0.444949
dtype: float64

丟棄有缺失值的行

planets.dropna().describe()
number orbital_period mass distance year
count 498.00000 498.000000 498.000000 498.000000 498.000000
mean 1.73494 835.778671 2.509320 52.068213 2007.377510
std 1.17572 1469.128259 3.636274 46.596041 4.167284
min 1.00000 1.328300 0.003600 1.350000 1989.000000
25% 1.00000 38.272250 0.212500 24.497500 2005.000000
50% 1.00000 357.000000 1.245000 39.940000 2009.000000
75% 2.00000 999.600000 2.867500 59.332500 2011.000000
max 6.00000 17337.500000 25.000000 354.000000 2014.000000

pandas的累計方法

指標 描述
count() 計數項
first(),last() 第一項與最後一項
mean(),median() 均值與中位數
min(),max() 最小值與最大值
std(),var() 標準差與方差
mad() 均值絕對偏差
prod() 所有項乘積
sum() 所有項求和

3.9.3 GrpupBy: 分隔, 應用和組合

df = pd.DataFrame({'key':['a','b','c','a','b','c'],
                  'data':range(6)})
df
key data
0 a 0
1 b 1
2 c 2
3 a 3
4 b 4
5 c 5
df.groupby('key')
<pandas.core.groupby.groupby.DataFrameGroupBy object at 0x000000F7FD8A1048>
df.groupby('key').sum()
data
key
a 3
b 5
c 7
df.groupby('key').mean()
data
key
a 1.5
b 2.5
c 3.5
df.groupby('key').last()
data
key
a 3
b 4
c 5

GroupBy中最重要的操作可能是aggregate, filter, transform和apply(累計,過濾,轉換,應用)

按列取值,返回修改過的GroupBy物件

planets.groupby('method')
<pandas.core.groupby.groupby.DataFrameGroupBy object at 0x000000F7FAA18E10>
planets.groupby('method')['orbital_period']
<pandas.core.groupby.groupby.SeriesGroupBy object at 0x000000F7FD8B90B8>
planets.groupby('method')['orbital_period'].median()
method
Astrometry                         631.180000
Eclipse Timing Variations         4343.500000
Imaging                          27500.000000
Microlensing                      3300.000000
Orbital Brightness Modulation        0.342887
Pulsar Timing                       66.541900
Pulsation Timing Variations       1170.000000
Radial Velocity                    360.200000
Transit                              5.714932
Transit Timing Variations           57.011000
Name: orbital_period, dtype: float64

按組迭代

for (method,group) in planets.groupby('method'):
    print("{0:30s}shape={1}".format(method, group.shape))    # 啥意思
Astrometry                    shape=(2, 6)
Eclipse Timing Variations     shape=(9, 6)
Imaging                       shape=(38, 6)
Microlensing                  shape=(23, 6)
Orbital Brightness Modulation shape=(3, 6)
Pulsar Timing                 shape=(5, 6)
Pulsation Timing Variations   shape=(1, 6)
Radial Velocity               shape=(553, 6)
Transit                       shape=(397, 6)
Transit Timing Variations     shape=(4, 6)

呼叫方法 - 用DataFrame的describe()方法進行累計, 對每一組資料進行描述性統計

planets.groupby('method')['year'].describe().unstack()
       method                       
count  Astrometry                          2.000000
       Eclipse Timing Variations           9.000000
       Imaging                            38.000000
       Microlensing                       23.000000
       Orbital Brightness Modulation       3.000000
       Pulsar Timing                       5.000000
       Pulsation Timing Variations         1.000000
       Radial Velocity                   553.000000
       Transit                           397.000000
       Transit Timing Variations           4.000000
mean   Astrometry                       2011.500000
       Eclipse Timing Variations        2010.000000
       Imaging                          2009.131579
       Microlensing                     2009.782609
       Orbital Brightness Modulation    2011.666667
       Pulsar Timing                    1998.400000
       Pulsation Timing Variations      2007.000000
       Radial Velocity                  2007.518987
       Transit                          2011.236776
       Transit Timing Variations        2012.500000
std    Astrometry                          2.121320
       Eclipse Timing Variations           1.414214
       Imaging                             2.781901
       Microlensing                        2.859697
       Orbital Brightness Modulation       1.154701
       Pulsar Timing                       8.384510
       Pulsation Timing Variations              NaN
       Radial Velocity                     4.249052
       Transit                             2.077867
       Transit Timing Variations           1.290994
                                           ...     
50%    Astrometry                       2011.500000
       Eclipse Timing Variations        2010.000000
       Imaging                          2009.000000
       Microlensing                     2010.000000
       Orbital Brightness Modulation    2011.000000
       Pulsar Timing                    1994.000000
       Pulsation Timing Variations      2007.000000
       Radial Velocity                  2009.000000
       Transit                          2012.000000
       Transit Timing Variations        2012.500000
75%    Astrometry                       2012.250000
       Eclipse Timing Variations        2011.000000
       Imaging                          2011.000000
       Microlensing                     2012.000000
       Orbital Brightness Modulation    2012.000000
       Pulsar Timing                    2003.000000
       Pulsation Timing Variations      2007.000000
       Radial Velocity                  2011.000000
       Transit                          2013.000000
       Transit Timing Variations        2013.250000
max    Astrometry                       2013.000000
       Eclipse Timing Variations        2012.000000
       Imaging                          2013.000000
       Microlensing                     2013.000000
       Orbital Brightness Modulation    2013.000000
       Pulsar Timing                    2011.000000
       Pulsation Timing Variations      2007.000000
       Radial Velocity                  2014.000000
       Transit                          2014.000000
       Transit Timing Variations        2014.000000
Length: 80, dtype: float64

累計,過濾,轉換和應用

GroupBy物件的aggregate(),filter(),transform()和apply()方法

import numpy as np
import pandas as pd
rng = np.random.RandomState(0)
df = pd.DataFrame({'key':['a','b','c','a','b','c'],
                  'data1':range(6),
                  'data2':rng.randint(0,10,6)},
                 columns = ['key','data1','data2'])
df
key data1 data2
0 a 0 5
1 b 1 0
2 c 2 3
3 a 3 3
4 b 4 7
5 c 5 9
df.groupby('key').aggregate(['min',np.median,max])
data1 data2
min median max min median max
key
a 0 1.5 3 3 4.0 5
b 1 2.5 4 0 3.5 7
c 2 3.5 5 3 6.0 9
df.groupby('key').aggregate([min,np.median,max])
data1 data2
min median max min median max
key
a 0 1.5 3 3 4.0 5
b 1 2.5 4 0 3.5 7
c 2 3.5 5 3 6.0 9
df.groupby('key').aggregate({'data1':min,
                            'data2':max})
data1 data2
key
a 0 5
b 1 7
c 2 9
def filter_func(x):
    return x['data2'].std()>4
print(df);print(df.groupby('key').std());
  key  data1  data2
0   a      0      5
1   b      1      0
2   c      2      3
3   a      3      3
4   b      4      7
5   c      5      9
       data1     data2
key                   
a    2.12132  1.414214
b    2.12132  4.949747
c    2.12132  4.242641
print(df.groupby('key').filter(filter_func))
  key  data1  data2
1   b      1      0
2   c      2      3
4   b      4      7
5   c      5      9

轉換

df.groupby('key').transform(lambda x: x - x.mean())
data1 data2
0 -1.5 1.0
1 -1.5 -3.5
2 -1.5 -3.0
3 1.5 -1.0
4 1.5 3.5
5 1.5 3.0

apply()方法

def norm_by_data2(x):
    x['data1'] /= x['data2'].sum()
    return x
print(df);print(df.groupby('key').apply(norm_by_data2))
  key  data1  data2
0   a      0      5
1   b      1      0
2   c      2      3
3   a      3      3
4   b      4      7
5   c      5      9
  key     data1  data2
0   a  0.000000      5
1   b  0.142857      0
2   c  0.166667      3
3   a  0.375000      3
4   b  0.571429      7
5   c  0.416667      9

設定分隔的鍵

l = [0,1,0,1,2,0]
print(df);print(df.groupby(l).sum())
  key  data1  data2
0   a      0      5
1   b      1      0
2   c      2      3
3   a      3      3
4   b      4      7
5   c      5      9
   data1  data2
0      7     17
1      4      3
2      4      7
df2 = df.set_index('key')
mapping = {'a':'vowel','b':'conn','c':'conn'}
print(df2);print(df2.groupby(mapping).sum())
     data1  data2
key              
a        0      5
b        1      0
c        2      3
a        3      3
b        4      7
c        5      9
       data1  data2
conn      12     19
vowel      3      8

任意Python函式

print(df2);print(df2.groupby(str.lower).mean())
     data1  data2
key              
a        0      5
b        1      0
c        2      3
a        3      3
b        4      7
c        5      9
   data1  data2
a    1.5    4.0
b    2.5    3.5
c    3.5    6.0

多個有效鍵構成的列表

df2.groupby([str.lower,mapping]).mean()
data1 data2
a vowel 1.5 4.0
b conn 2.5 3.5
c conn 3.5 6.0

分組案例

decade = 10 * (planets['year']//10)
decade = decade.astype(str) + 's'
decade.name = 'decade'
planets.groupby(['method',decade])['number'].sum().unstack().fillna(0)
decade 1980s 1990s 2000s 2010s
method
Astrometry 0.0 0.0 0.0 2.0
Eclipse Timing Variations 0.0 0.0 5.0 10.0
Imaging 0.0 0.0 29.0 21.0
Microlensing 0.0 0.0 12.0 15.0
Orbital Brightness Modulation 0.0 0.0 0.0 5.0
Pulsar Timing 0.0 9.0 1.0 1.0
Pulsation Timing Variations 0.0 0.0 1.0 0.0
Radial Velocity 1.0 52.0 475.0 424.0
Transit 0.0 0.0 64.0 712.0
Transit Timing Variations 0.0 0.0 0.0 9.0

3.10 資料透視表

- 資料透視表更像是一種多維的GroupBy累計操作.
import numpy as np
import pandas as pd
import seaborn as sns
titanic = sns.load_dataset('titanic')
titanic.head()
survived pclass sex age sibsp parch fare embarked class who adult_male deck embark_town alive alone
0 0 3 male 22.0 1 0 7.2500 S Third man True NaN Southampton no False
1 1 1 female 38.0 1 0 71.2833 C First woman False C Cherbourg yes False
2 1 3 female 26.0 0 0 7.9250 S Third woman False NaN Southampton yes True
3 1 1 female 35.0 1 0 53.1000 S First woman False C Southampton yes False
4 0 3 male 35.0 0 0 8.0500 S Third man True NaN Southampton no True

3.10.2 手工製作資料透視表

# 不同性別的生還率
titanic.groupby('sex')['survived'].mean()
sex
female    0.742038
male      0.188908
Name: survived, dtype: float64
# 之前內容介紹的方法
titanic.groupby(['sex','class'])['survived'].aggregate('mean').unstack()
class First Second Third
sex
female 0.968085 0.921053 0.500000
male 0.368852 0.157407 0.135447

3.10.3 資料透視表語法

用DataFrame的pivot_table實現的效果等同於上一節管道命令的程式碼

titanic.pivot_table('survived',index='sex',columns='class')
class First Second Third
sex
female 0.968085 0.921053 0.500000
male 0.368852 0.157407 0.135447

多級資料透視表

# 利用pd.cut函式對年齡進行分段
age = pd.cut(titanic['age'],[0,18,80])   #結果class列怎麼和書上不一樣
titanic.pivot_table('survived',['sex',age],'class')
class First Second Third
sex age
female (18, 80] 0.909091 1.000000 0.511628
NaN 0.972973 0.900000 0.423729
male (18, 80] 0.800000 0.600000 0.215686
NaN 0.375000 0.071429 0.133663
# 用pd.qcut將船票價格按照計數項分為兩項
fare = pd.qcut(titanic['fare'],2)
titanic.pivot_table('survived',['sex',age],[fare,'class'])
fare (-0.001, 14.454] (14.454, 512.329]
class First Second Third First Second Third
sex age
female (18, 80] NaN 1.000000 0.714286 0.909091 1.000000 0.318182
NaN NaN 0.880000 0.444444 0.972973 0.914286 0.391304
male (18, 80] NaN 0.000000 0.260870 0.800000 0.818182 0.178571
NaN 0.0 0.098039 0.125000 0.391304 0.030303 0.192308

其他資料透視表選項

DataFrame的pivot_table方法的完整簽名如下: - DataFrame.pivot_table(data, value=None, index=None, columns=None, aggfunc='mean, fill_value=None, margins=False, dropna=True, margins_name=‘ALL’) - fill_value和dropna用於處理缺失值 - aggfunc引數用於設定累計函式的型別, 預設是均值(mean), 與GroupBy的用法一樣,也可以是sum, count,min,max. 還可以通過字典方法指定

titanic.pivot_table(index='sex',columns='class',
                   aggfunc={'survived':sum,'fare':'mean'})     # mean需要寫成字串形式
fare survived
class First Second Third First Second Third
sex
female 106.125798 21.970121 16.118810 91 70 72
male 67.226127 19.741782 12.661633 45 17 47

當需要計算每一組的總數時, 可以通過margins引數來設定

titanic.pivot_table('survived',index='sex',columns='class',margins=True)
class First Second Third All
sex
female 0.968085 0.921053 0.500000 0.742038
male 0.368852 0.157407 0.135447 0.188908
All 0.629630 0.472826 0.242363 0.383838

3.10.4 美國人的生日

births = pd.read_csv('e:/python/births.csv')
births.head()
year month day gender births
0 1969 1 1.0 F 4046
1 1969 1 1.0 M 4440
2 1969 1 2.0 F 4454
3 1969 1 2.0 M 4548
4 1969 1 3.0 F 4548
births['decade'] = 10 * (births['year']//10)
births.pivot_table('births',index='decade',columns='gender',aggfunc='sum')
gender F M
decade
1960 1753634 1846572
1970 16263075 17121550
1980 18310351 19243452
1990 19479454 20420553
2000 18229309 19106428
%matplotlib inline
import matplotlib.pyplot as plt
sns.set()  # 使用seaborn風格
births.pivot_table('births', index='year',columns='gender',aggfunc='sum').plot()
plt.ylabel('total births per year')
Text(0,0.5,'total births per year')

png

quartiles = np.percentile(births['births'],[25,50,75])
mu = quartiles[1]
sig = 0.74 * (quartiles[2] - quartiles[0])
births = births.query('(births > @mu - 5 * @sig) & (births < @mu + 5 * @sig)')
births['day'] = births['day'].astype(int)
births.index = pd.to_datetime(10000 * births.year +          # 乘以1萬
                             100 * births.month + 
                             births.day, format='%Y%m%d')
births['dayofweek'] = births.index.dayofweek
import matplotlib.pyplot as plt
import matplotlib as mpl
births.pivot_table('births',index='dayofweek',
                  columns='decade',aggfunc='mean').plot()
plt.gca().set_xticklabels(['Mon','Tues','Wed','Thurs','Fri','Ssat','Sun'])
plt.ylabel('mean births by day')
Text(0,0.5,'mean births by day')

png

births_by_date = births.pivot_table('births',
                                   [births.index.month
            
           

相關推薦

3 Pandas資料處理(3.9-3.10)_Python資料科學手冊學習筆記

3.9 累計與分組 3.9.1 行星資料 import seaborn as sns planets = sns.load_dataset('planets') planets.shape (1035, 6) planets.head()

3 Pandas資料處理(3.1-3.2)_Python資料科學手冊學習筆記

第2章介紹的NumPy和它的ndarray物件. 為多維陣列提供了高效的儲存和處理方法. Pandas是在NumPy的基礎上建立的新程式庫, 提供DataFrame資料結構. DataFrame帶行標籤(索引),列標籤(變數名),支援相同資料型別和缺失值的多維陣

3 Pandas資料處理(3.4-3.5)_Python資料科學手冊學習筆記

3.4 Pandas 數值運算方法 對於一元運算(像函式與三角函式),這些通用函式將在輸出結果中保留索引和列標籤; 而對於二元運算(如加法和乘法), Pandas在傳遞通用函式時會自動對齊索引進行計算. 這就意味著,儲存資料內容和組合不同來源的資料—兩處在Num

3 Pandas資料處理(3.3)_Python資料科學手冊學習筆記

3.3 資料取值與選擇 第2章回顧: - NumPy中取值操作: arr[2,1] - 切片操作: arr[:,1:5] - 掩碼操作: arr[arr>0] - 花哨的索引操作: arr[0,[1,5]] - 組合操作: arr[:,[1:5]] 3.3

3 Pandas資料處理(3.7-3.8)_Python資料科學手冊學習筆記

3.7 合併資料集: Concat與Append操作 - pd.concat - pd.merge - pd.join import pandas as pd def make_df(cols,ind): data = {c: [str(c) + st

Libgdx輸入處理9)選單捕獲

Android遊戲開發群:290051794 Libgdx遊戲開發框架交流群:261954621 在Android中,當用戶按下返回鍵,這樣通常會關閉正在執行的Activity。遊戲通常會在退出之前

Python資料科學手冊學習筆記

Numpy入門 檢視numpy版本 import numpy numpy.__version__ 2.匯入numpy的匯入 import numpy as np 3.建立陣列 import nu

資料基礎---《利用Python進行資料分析·2版》12 pandas高階應用

之前自己對於numpy和pandas是要用的時候東學一點西一點,直到看到《利用Python進行資料分析·第2版》,覺得只看這一篇就夠了。非常感謝原博主的翻譯和分享。 前面的章節關注於不同型別的資料規整流程和NumPy、pandas與其它庫的特點。隨著時間的發展,pandas發展出了更多適

資料基礎---《利用Python進行資料分析·2版》5 pandas入門

之前自己對於numpy和pandas是要用的時候東學一點西一點,直到看到《利用Python進行資料分析·第2版》,覺得只看這一篇就夠了。非常感謝原博主的翻譯和分享。 pandas是本書後續內容的首選庫。它含有使資料清洗和分析工作變得更快更簡單的資料結構和操作工具。pandas經常和其它工

易學筆記-計算機底層-1:計算機系統漫遊/1.3 瞭解編譯系統的作用

瞭解編譯系統的作用 優化程式效能,特別是C語言,不同的寫法編譯器翻譯不同的結果,導致不同的執行效率 switch語句為什麼比if-else更加有效 while迴圈比for迴圈更有效 指標引用比陣列應用更有效 連結出現的錯誤

作業系統 2 程序管理 2.2 2.3

** 2.2程序控制 ** 一、程序控制的基本過程: 1、1)程序的建立(一個程序建立另一程序的事件(原因)) 使用者登入:分時情況下使用者的請求 作業排程:批處理中 提供服務:執行中的使用者程式提出功能請求,要建立服務程序(如列印服務) 應用請求:應用程式自己建立程序,完成特定功能

11 拾遺4:IPv6(3)_配置IPv6路由

5. 配置IPv6路由 5.1 配置IPv6靜態路由 (1)在路由器上配置靜態路由(以R1路由器為例) //靜態路由 R1#config t R1(config)#ipv6 unicast-routing //啟用IPv6路由功能 R1(config)#ipv6 route

spring-bean之DefaultSingletonBeanRegistry(3

前言 SingletonBeanRegistry是一個非常重要的介面,用於註冊,獲得,管理singleton物件。 SingletonBeanRegistry目前唯一的實現是DefaultSingletonBeanRegistry,DefaultSingletonBea

爬取了 48048 條評論資料,解讀 9.3 分的《毒液》是否值得一看?

11月,由湯姆·哈迪主演的“毒液:致命守護者”在國內上映,依託漫威的光環以及演員們精湛的演技,這部動作科幻片在貓眼評分得到豆瓣7.4的評分,口碑和票房都高於大多數同期上映的其他影片。 所以週日的時候跟基友去電影院去看了這場正邪共生的電影,100多人的影院座無虛席,不過看完之後對比其他漫威作品

資料教程(9.3)MR執行在yarn叢集流程分析&&本地模式除錯MR程式_

       mapreduce在yarn叢集中流程分析:         在windows本地環境的除錯需要先安裝好windows環境,具體請看windows安裝篇;

資料教程(9.3)MR執行在yarn叢集流程分析&&本地模式除錯MR程式_

       mapreduce在yarn叢集中流程分析:         在windows本地環境的除錯需要先安裝好windows環境,具體請看windows安裝篇;  

《java程式設計思想》四版 2 一切都是物件 2 . 3 絕對不要清除物件

在大多數程式設計語言中,變數的“存在時間”(Lifetime)一直是程式設計師需要著重考慮的問題。變數應持 續多長的時間?如果想清除它,那麼何時進行?在變數存在時間上糾纏不清會造成大量的程式錯誤。在下面 的小節裡,將闡示Java 如何幫助我們完成所有清除工作

R:ggplot2(7),4 用圖形構建影象(3

《ggplot2:資料分析與圖形藝術》 第4章 用圖形構建影象 4.6 幾何物件 幾何圖形物件,簡稱為geom,它執行著圖層的實際渲染,控制著生成的影象型別。表4.2列出了ggplot2裡面所有可用的幾

自然語言處理-概括資料-資料清洗加去掉常規詞語

#!/usr/bin/env python # _*_ coding:utf-8 _*_ import operator import re import string from collections import OrderedDict from urllib.reque

python cookbook 學習筆記 數字日期和時間(9) 大型資料運算

大型資料運算 -問題: 需要在大資料集(比如陣列或網路)上面執行計算。 解決方案: 涉及到陣列的重量級運算,可以使用 Numpy 庫。Numpy 的一個主要特徵是他會給 Python 提 供一個數組物件,相比標準的 Python 列表更適合用來做數學運