重新研讀fish千聊課07 (上)

這次開始之前,我自己有必要先分析一下思路,再開始研讀,到目前為止,我研讀這些東西,都沒有跟實(shí)際工作生活像結(jié)合起來,還是有一種為了學(xué)東西,而學(xué)東西。

我學(xué)這個(gè)有什么用呢?

這是沒能想清楚的問題. 學(xué)了python的這點(diǎn)課,真的可能成為我未來轉(zhuǎn)行大數(shù)據(jù)行業(yè)的技能儲(chǔ)備嗎?

有時(shí)候會(huì)覺得自己很幼稚。

但也一直覺得,能接觸到這項(xiàng)技能真的很有意義。

是不是我把學(xué)習(xí)Python技能,強(qiáng)制附加了“成為未來轉(zhuǎn)行的必備技能”的期望,而失去了學(xué)習(xí)東西的那份快樂呢?

好吧,廢話幾句。 不知道,接下來關(guān)于大數(shù)據(jù)的學(xué)習(xí),該何去何從,接著研讀吧。

import pandas as pd
import numpy as np
import scipy.stats
import matplotlib.pyplot as plt
import matplotlib  # ?? 只引用matplotlib 和.pyplot 之間的區(qū)別是什么呢?
matplotlib.style.use('ggplot')

%matplotlib inline
#%config BackendInline.forture_commat('retina')
#%config InlineBackend.fortune_format = 'retina'
#
%config InlineBackend.figure_format = 'retina'

#錯(cuò)誤記錄: 配置圖形格式為retina這段代碼,總是寫錯(cuò)。 1. figure_format ,拼寫錯(cuò)誤明顯。 2. 不是用括號(hào),而是直接等于。
# 新增知識(shí)點(diǎn): ggplot,是一個(gè)r語(yǔ)言的圖形繪制包,可以像圖層一樣繪制,很好用。

/home/bobo/anaconda3/lib/python3.6/site-packages/matplotlib/font_manager.py:280: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  'Matplotlib is building the font cache using fc-list. '
!ls data

data_75_12.csv  evolution.csv  fortis_heritability.csv

我不能在自己電腦上直接使用帶感嘆號(hào)的方式運(yùn)行l(wèi)inux命令。 但是去掉感嘆號(hào)后,卻出現(xiàn)了比較多的文件夾信息。

數(shù)據(jù)導(dǎo)入和清洗

這部分主要是把粗糙的數(shù)據(jù)進(jìn)行清洗

evolution = pd.read_csv(r'data/evolution.csv')

錯(cuò)誤記錄:

  1. 代碼和文件沒有在同一層文件夾中,所以應(yīng)該加入文件夾地址“data/”,我天真地以為可以直接導(dǎo)入
  2. csv,被我搞成了scv
evolution.head()
evolution.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 83 entries, 0 to 82
Data columns (total 8 columns):
Year              82 non-null object
Species           81 non-null object
Beak length       81 non-null object
Beak depth        80 non-null float64
Beak width        80 non-null float64
CI Beak length    80 non-null object
CI Beak depth     80 non-null object
CI Beak width     80 non-null object
dtypes: float64(2), object(6)
memory usage: 5.3+ KB

只有兩個(gè)數(shù)字是float類型,還有絕大部分?jǐn)?shù)據(jù)都不是82個(gè)。

evolution = evolution.dropna()
evolution.info()

新增知識(shí)點(diǎn):
data.dropna() 是刪除缺失值的方法,把數(shù)值不齊全的列給刪除掉。

<class 'pandas.core.frame.DataFrame'>
Int64Index: 80 entries, 0 to 82
Data columns (total 8 columns):
Year              80 non-null object
Species           80 non-null object
Beak length       80 non-null object
Beak depth        80 non-null float64
Beak width        80 non-null float64
CI Beak length    80 non-null object
CI Beak depth     80 non-null object
CI Beak width     80 non-null object
dtypes: float64(2), object(6)
memory usage: 5.6+ KB
#evolution['Beak length']= pd.numeric['Beak length']

evolution['Beak length'] = pd.to_numeric(evolution['Beak length'])
evolution['Beak length'].head()

錯(cuò)誤記錄:
1 . 轉(zhuǎn)換為數(shù)值類型需要有對(duì)象啊。 對(duì)象一半都在括號(hào)中。 我現(xiàn)在感覺python很像是一個(gè)超大的工具包,我說我要A工具,它流把掏出來,不過工具太多,我得說明白
所以我要說,我需要用A工具去操作對(duì)象a.

  1. 轉(zhuǎn)換為什么的話,是需要加to的,我并沒有加,也就是基本的拼寫錯(cuò)誤。
0    10.76
1    10.72
2    10.57
3    10.64
4    10.73
Name: Beak length, dtype: float64
evolution['CI Beak length'] = pd.to_numeric(evolution['CI Beak length'],errors='coerce')

evolution['CI Beak depth'] = pd.to_numeric(evolution['CI Beak depth'],errors='coerce')
evolution['CI Beak width'] = pd.to_numeric(evolution['CI Beak width'],errors='coerce')

新增知識(shí)點(diǎn):強(qiáng)制轉(zhuǎn)化為數(shù)據(jù)類型,但遇到不能轉(zhuǎn)化的額,就用null代替

evolution.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 80 entries, 0 to 82
Data columns (total 8 columns):
Year              80 non-null object
Species           80 non-null object
Beak length       80 non-null float64
Beak depth        80 non-null float64
Beak width        80 non-null float64
CI Beak length    79 non-null float64
CI Beak depth     79 non-null float64
CI Beak width     79 non-null float64
dtypes: float64(6), object(2)
memory usage: 5.6+ KB

初步的數(shù)據(jù)清洗,就完成了,若是要?jiǎng)h除某些列呢? 該咋辦呀?

數(shù)據(jù)探索

evolution.head()
evolution.tail()
evolution.Species.value_counts()

錯(cuò)誤記錄: value——count可是只針對(duì)一列的匯總統(tǒng)計(jì),我輸入的是evolution.value_counts()對(duì)象是整個(gè)數(shù)據(jù)啊,而我只是想要其中的一列

fortis      40
scandens    40
Name: Species, dtype: int64

嘗試修改列名稱
evolution.rename(columns = {'Species':'species'},inplace=True)

錯(cuò)誤記錄,未加引號(hào)

evolution.head()

fortis = evolution[evolution.species=='fortis']
fortis.tail()
scandens = evolution[evolution.species=='scandens']
scandens.tail()

所有方括號(hào)的外的數(shù)據(jù),給定了范圍,方括號(hào)內(nèi),就是篩選數(shù)據(jù)范圍。
evolution.species[evolution.species=='scandens'] vs
evolution[evolution.species=='scandens'] 是截然不同的結(jié)果

fortis.plot(x='Year',y=['Beak length','Beak depth','Beak width'])

錯(cuò)誤記錄:

  1. y= 后面只能有一個(gè)對(duì)象,我的逗號(hào),就反映了有多個(gè)對(duì)象,應(yīng)該把多個(gè)對(duì)象用方括號(hào)連起來。
  2. 我竟然直接開始畫圖,用plt.plot開頭,連data都沒有。 應(yīng)該是fortis.plot,笨!!
<matplotlib.axes._subplots.AxesSubplot at 0xa4d6128>
output_22_1.png
scandens.plot(x='Year',y=['Beak length','Beak depth','Beak width'])
<matplotlib.axes._subplots.AxesSubplot at 0xa9006d8>
output_23_1.png
output_24_1.png
scandens.plot(x='Year',y=['Beak length','Beak depth','Beak width'],subplots = True,figsize=(10,6))
#新增知識(shí)點(diǎn):1.subplots,意思應(yīng)該是在多幅圖上作圖,而非在一張圖上顯示
array([<matplotlib.axes._subplots.AxesSubplot object at 0x000000000BA26898>,
       <matplotlib.axes._subplots.AxesSubplot object at 0x000000000BB0FC88>,
       <matplotlib.axes._subplots.AxesSubplot object at 0x000000000BB5F240>], dtype=object)
output_24_1.png
fortis.plot(x='Year',y='Beak depth',yerr='CI Beak depth',color='Red',marker='o',figsize=(10,5))

新增知識(shí)點(diǎn):yerr,marker

<matplotlib.axes._subplots.AxesSubplot at 0xd339b00>
output_25_1.png
scandens.plot(x='Year',y='Beak depth',yerr='CI Beak depth',color='Orange',marker='o',figsize=(11,4))
<matplotlib.axes._subplots.AxesSubplot at 0xe03fc88>
output_26_1.png

75年和12年的數(shù)據(jù)比較

ls data
 驅(qū)動(dòng)器 C 中的卷是 WIN7
 卷的序列號(hào)是 CCED-57EE

 C:\Users\Administrator.USER-20170623BT\Desktop\第七課材料\第七課材料\codes\data 的目錄

2017/08/31  12:13    <DIR>          .
2017/08/31  12:13    <DIR>          ..
2017/08/14  17:39             6,148 .DS_Store
2017/08/14  12:37            14,142 data_75_12.csv
2017/08/14  17:50             3,930 evolution.csv
2017/08/14  13:15             8,568 fortis_heritability.csv
               4 個(gè)文件         32,788 字節(jié)
               2 個(gè)目錄 40,499,621,888 可用字節(jié)
data = pd.read_csv('data/data_75_12.csv')
data.head()

這組數(shù)據(jù)中只包含有75年和12年的所有樣本,而剛才的是每年的數(shù)據(jù)一個(gè)均值。

data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 651 entries, 0 to 650
Data columns (total 4 columns):
species    651 non-null object
length     651 non-null float64
depth      651 non-null float64
year       651 non-null int64
dtypes: float64(2), int64(1), object(1)
memory usage: 20.4+ KB
data.year.value_counts()
1975    403
2012    248
Name: year, dtype: int64
data.species.value_counts()
fortis      437
scandens    214
Name: species, dtype: int64
data.groupby(['species','year']).count()

錯(cuò)誤記錄:

  1. groupby后面的對(duì)象應(yīng)該是括號(hào)啊,用方括號(hào),往往都是為了把多個(gè)數(shù)據(jù),合并為一個(gè)對(duì)象。
  2. groupby的計(jì)數(shù),是不加s的。
data.groupby(['species','year']).mean()
fortis2 = data[data.species=='fortis']
fortis2.head()
fortis2.boxplot(by='year',figsize=(10,5))
array([<matplotlib.axes._subplots.AxesSubplot object at 0x7fca6a16c630>,
       <matplotlib.axes._subplots.AxesSubplot object at 0x7fca615bcfd0>], dtype=object)
output_37_1.png
scandens2 = data[data.species=='scandens']
scandens2.head()

scandens2.boxplot(by='year',figsize=(10,5))
array([<matplotlib.axes._subplots.AxesSubplot object at 0x7fca610619e8>,
       <matplotlib.axes._subplots.AxesSubplot object at 0x7fca61493438>], dtype=object)
output_39_1.png

中地雀鳥喙深度和長(zhǎng)度的變化


按時(shí)間給中地雀的樣本分組
fortis75 = fortis2[fortis2.year==1975]
為什么對(duì)時(shí)間的切片,不用加引號(hào)呢? 引號(hào)只是對(duì)str類型有效嗎?
fortis12 = fortis2[fortis2.year==2012]

print (fortis75.head())
print (fortis12.head())
  species  length  depth  year
0  fortis     9.4    8.0  1975
1  fortis     9.2    8.3  1975
2  fortis     9.5    7.5  1975
3  fortis     9.5    8.0  1975
4  fortis    11.5    9.9  1975
    species  length  depth  year
403  fortis    10.0    8.5  2012
404  fortis    12.5    8.9  2012
405  fortis     9.3    7.5  2012
406  fortis    10.3    9.6  2012
407  fortis    11.0    9.2  2012

個(gè)人思考:這里的fortis75 和fortis12 是兩組抽樣分布,所以我們要比較兩組分布之間的數(shù)據(jù)變化,是需要用推論統(tǒng)計(jì)的。
而比較兩組數(shù)據(jù)間的差別應(yīng)該怎么辦呢?
核心指標(biāo)是什么???
是總體的均值。
但是總體的均值,是一個(gè)推測(cè)值,由兩組樣本之間的推測(cè)出的總體均值的范圍來確定的。
所以需要用置信區(qū)間來確定,鎖定在大部分情況下,總體均值會(huì)在什么范圍。

但是比較兩個(gè)樣本的總體均值的話,該怎么辦?

那就是用拒絕域的那個(gè)觀點(diǎn),可是拒絕域的本質(zhì)問題是什么???
p value,還有μ的范圍。

頭腦有點(diǎn)炸 ,我看看源碼吧,

fortis75.depth.mean()
9.171645569620255
fortis12.depth.mean()
8.605371900826446
def mean_ci(data):
    #均值95%的置信區(qū)間
    n  = len(data)
    x_ = np.mean(data)
    s = np.std(data,ddof=1)
    z = scipy.stats.norm.isf(0.0025)
    se = s/np.sqrt(n)
    con_in = (x_-z*se,x_+z*se)
    
    return con_in
mean_ci(fortis75.depth)
(9.0552111088224159, 9.2880800304180937)
def mean_ci1(data):    
    '''給定樣本數(shù)據(jù),計(jì)算均值95%的置信區(qū)間'''        
    sample_size = len(data)    
    std = np.std(data, ddof=1)     
    se = std / np.sqrt(sample_size)        
    point_estimate = np.mean(data)      
    z_score = scipy.stats.norm.isf(0.025)  # 置信度95%    
    confidence_interval = (point_estimate - z_score * se, point_estimate + z_score * se)    
    
    return confidence_interval
mean_ci1(fortis75.depth)
(9.0903471711839057, 9.2529439680566039)
mean_ci(fortis12.depth)
(8.4184311775393894, 8.792312624113503)
mean_ci1(fortis12.depth)
(8.4748436937850755, 8.7359001078678169)

鳥喙深度均值差

也就是說,拿75年和12年的均值相減。

diff_mean = fortis12.depth.mean()-fortis75.depth.mean()
diff_mean

-0.5662736687938086

bootstrap求差值的均值變化

def draw_bs_res(data,func,size = 1):
    bs_replicates = np.empty(size)  #錯(cuò)誤記錄,np.empy()括號(hào)中還需要情況一個(gè)值,那就是size。 既然初始化,那一定要指明初始化的是哪個(gè)數(shù)字哦
    for i in range(size):
        bs_replicates[i] = func(np.random.choice(data,size = len(data)))#choice()后面是有2個(gè)參數(shù),樣本是哪些? 從樣本中再抽多少次?而我只是把樣本放進(jìn)去了,忘了寫該抽樣多少個(gè)
        
    return bs_replicates
bs_for75=draw_bs_res(fortis75.depth,np.mean, 10000)
bs_for12 = draw_bs_res(fortis12.depth,np.mean,10000)

bs_for75
array([ 9.24414557,  9.20844937,  9.23446203, ...,  9.19316456,
        9.12177215,  9.22363924])
bs_for12
array([ 8.57479339,  8.5731405 ,  8.62190083, ...,  8.72933884,
        8.76115702,  8.60330579])
diff_bs = bs_for12-bs_for75
diff_bs
array([-0.66935218, -0.63530887, -0.6125612 , ..., -0.46382571,
       -0.36061513, -0.62033346])
diff_mean = np.percentile(diff_bs,[2.5,97.5])
diff_mean
array([-0.71902047, -0.40750995])
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1. 簡(jiǎn)述相關(guān)分析和回歸分析的區(qū)別和聯(lián)系。 回歸分析和相關(guān)分析都是研究?jī)蓚€(gè)或兩個(gè)以上變量之間關(guān)系的方法。 廣義上說...
    安也也閱讀 9,162評(píng)論 0 3
  • 這次開始之前,我自己有必要先分析一下思路,再開始研讀,到目前為止,我研讀這些東西,都沒有跟實(shí)際工作生活像結(jié)合起來,...
    Bog5d閱讀 230評(píng)論 0 0
  • 本課主要是統(tǒng)計(jì)學(xué)常識(shí)。 很多概念都值得背誦下來。 描述統(tǒng)計(jì)量 集中趨勢(shì)均值中位數(shù)眾數(shù) 離散程度全距四分位距方差、...
    Bog5d閱讀 517評(píng)論 0 0
  • 《R語(yǔ)言與統(tǒng)計(jì)分析》的讀書筆記 本書的重點(diǎn)內(nèi)容及感悟: 第三章 概率與分布 1、隨機(jī)抽樣 通過sample()來實(shí)...
    格式化_001閱讀 7,010評(píng)論 1 12
  • Guess what is this? Do you know Tom and Jack? Tom in this!
    玥光下的貓閱讀 220評(píng)論 0 1

友情鏈接更多精彩內(nèi)容