文章轉(zhuǎn)載自Google,最近更新:2018-07-25
Google上線了一個(gè)“機(jī)器學(xué)習(xí)速成課程”风秤,英文簡(jiǎn)稱MLCC又活。這個(gè)課程節(jié)奏緊湊佃却、內(nèi)容實(shí)用岔激。課程基本可以全程中文(包括視頻),免費(fèi),并且有相關(guān)的練習(xí).
如果可以翻墻的小伙伴,可以看看,鏈接如下:機(jī)器學(xué)習(xí)速成課程
Pandas 是用于進(jìn)行數(shù)據(jù)分析和建模的重要庫(kù),廣泛應(yīng)用于 TensorFlow 編碼遇八。該教程提供了您學(xué)習(xí)本課程所需的全部 Pandas 信息矛绘。如果您已了解 Pandas,則可以跳過(guò)此練習(xí)刃永。
1.Pandas 簡(jiǎn)介
學(xué)習(xí)目標(biāo):
- 大致了解 pandas 庫(kù)的 DataFrame 和 Series 數(shù)據(jù)結(jié)構(gòu)
- 存取和處理 DataFrame 和 Series 中的數(shù)據(jù)
- 將 CSV 數(shù)據(jù)導(dǎo)入 pandas 庫(kù)的 DataFrame
- 對(duì) DataFrame 重建索引來(lái)隨機(jī)打亂數(shù)據(jù)
pandas 是一種列存數(shù)據(jù)分析 API货矮。它是用于處理和分析輸入數(shù)據(jù)的強(qiáng)大工具,很多機(jī)器學(xué)習(xí)框架都支持將 pandas 數(shù)據(jù)結(jié)構(gòu)作為輸入斯够。 雖然全方位介紹 pandas API 會(huì)占據(jù)很長(zhǎng)篇幅囚玫,但它的核心概念非常簡(jiǎn)單,我們會(huì)在下文中進(jìn)行說(shuō)明读规。有關(guān)更完整的參考抓督,請(qǐng)?jiān)L問(wèn) pandas 文檔網(wǎng)站,其中包含豐富的文檔和教程資源束亏。
2.基本概念
以下行導(dǎo)入了 pandas API 并輸出了相應(yīng)的 API 版本:
import pandas as pd
pd.__version__
pandas 中的主要數(shù)據(jù)結(jié)構(gòu)被實(shí)現(xiàn)為以下兩類(lèi):
-
DataFrame
铃在,您可以將它想象成一個(gè)關(guān)系型數(shù)據(jù)表格,其中包含多個(gè)行和已命名的列碍遍。 -
Series
定铜,它是單一列。DataFrame
中包含一個(gè)或多個(gè)Series
怕敬,每個(gè)Series
均有一個(gè)名稱揣炕。
數(shù)據(jù)框架是用于數(shù)據(jù)操控的一種常用抽象實(shí)現(xiàn)形式。Spark 和 R 中也有類(lèi)似的實(shí)現(xiàn)东跪。
創(chuàng)建 Series 的一種方法是構(gòu)建 Series 對(duì)象祝沸。例如:
pd.Series(['San Francisco', 'San Jose', 'Sacramento'])
0 San Francisco
1 San Jose
2 Sacramento
dtype: object
您可以將映射 string
列名稱的 dict
傳遞到它們各自的 Series
,從而創(chuàng)建DataFrame
對(duì)象越庇。如果 Series
在長(zhǎng)度上不一致罩锐,系統(tǒng)會(huì)用特殊的 NA/NaN 值填充缺失的值。例如:
city_names = pd.Series(['San Francisco', 'San Jose', 'Sacramento'])
population = pd.Series([852469, 1015785, 485199])
pd.DataFrame({ 'City name': city_names, 'Population': population })
City name Population
0 San Francisco 852469
1 San Jose 1015785
2 Sacramento 485199
但是在大多數(shù)情況下卤唉,您需要將整個(gè)文件加載到 DataFrame 中涩惑。下面的示例加載了一個(gè)包含加利福尼亞州住房數(shù)據(jù)的文件。請(qǐng)運(yùn)行以下單元格以加載數(shù)據(jù)桑驱,并創(chuàng)建特征定義:
california_housing_dataframe = pd.read_csv("https://storage.googleapis.com/mledu-datasets/california_housing_train.csv", sep=",")
california_housing_dataframe.describe()
longitude latitude housing_median_age total_rooms total_bedrooms population households median_income median_house_value
count 17000.000000 17000.000000 17000.000000 17000.000000 17000.000000 17000.000000 17000.000000 17000.000000 17000.000000
mean -119.562108 35.625225 28.589353 2643.664412 539.410824 1429.573941 501.221941 3.883578 207300.912353
std 2.005166 2.137340 12.586937 2179.947071 421.499452 1147.852959 384.520841 1.908157 115983.764387
min -124.350000 32.540000 1.000000 2.000000 1.000000 3.000000 1.000000 0.499900 14999.000000
25% -121.790000 33.930000 18.000000 1462.000000 297.000000 790.000000 282.000000 2.566375 119400.000000
50% -118.490000 34.250000 29.000000 2127.000000 434.000000 1167.000000 409.000000 3.544600 180400.000000
75% -118.000000 37.720000 37.000000 3151.250000 648.250000 1721.000000 605.250000 4.767000 265000.000000
max -114.310000 41.950000 52.000000 37937.000000 6445.000000 35682.000000 6082.000000 15.000100 500001.000000
上面的示例使用 DataFrame.describe 來(lái)顯示關(guān)于 DataFrame 的有趣統(tǒng)計(jì)信息竭恬。另一個(gè)實(shí)用函數(shù)是 DataFrame.head,它顯示 DataFrame 的前幾個(gè)記錄:
california_housing_dataframe.head()
longitude latitude housing_median_age total_rooms total_bedrooms population households median_income median_house_value
0 -114.31 34.19 15.0 5612.0 1283.0 1015.0 472.0 1.4936 66900.0
1 -114.47 34.40 19.0 7650.0 1901.0 1129.0 463.0 1.8200 80100.0
2 -114.56 33.69 17.0 720.0 174.0 333.0 117.0 1.6509 85700.0
3 -114.57 33.64 14.0 1501.0 337.0 515.0 226.0 3.1917 73400.0
4 -114.57 33.57 20.0 1454.0 326.0 624.0 262.0 1.9250 65500.0
pandas 的另一個(gè)強(qiáng)大功能是繪制圖表赊级。例如理逊,借助 DataFrame.hist晋被,您可以快速了解一個(gè)列中值的分布:
california_housing_dataframe.hist('housing_median_age')
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7f0054553710>]],
dtype=object)
2.訪問(wèn)數(shù)據(jù)
您可以使用熟悉的 Python dict/list 指令訪問(wèn) DataFrame 數(shù)據(jù):
案例1
cities = pd.DataFrame({ 'City name': city_names, 'Population': population })
print type(cities['City name'])
cities['City name']
<class 'pandas.core.series.Series'>
0 San Francisco
1 San Jose
2 Sacramento
Name: City name, dtype: object
案例2
print type(cities['City name'][1])
cities['City name'][1]
<type 'str'>
'San Jose'
案例3
print type(cities[0:2])
cities[0:2]
<class 'pandas.core.frame.DataFrame'>
City name Population
0 San Francisco 852469
1 San Jose 1015785
此外藕漱,pandas 針對(duì)高級(jí)索引和選擇提供了極其豐富的 API(數(shù)量過(guò)多肋联,此處無(wú)法逐一列出)。
3.操控?cái)?shù)據(jù)
您可以向 Series 應(yīng)用 Python 的基本運(yùn)算指令。例如:
population / 1000
0 852.469
1 1015.785
2 485.199
dtype: float64
NumPy 是一種用于進(jìn)行科學(xué)計(jì)算的常用工具包沙兰。pandas Series
可用作大多數(shù) NumPy 函數(shù)的參數(shù):
import numpy as np
np.log(population)
0 13.655892
1 13.831172
2 13.092314
dtype: float64
對(duì)于更復(fù)雜的單列轉(zhuǎn)換,您可以使用 Series.apply
斋射。像 Python 映射函數(shù)一樣罗岖,Series.apply
將以參數(shù)形式接受 lambda 函數(shù)桑包,而該函數(shù)會(huì)應(yīng)用于每個(gè)值哑了。
下面的示例創(chuàng)建了一個(gè)指明 population
是否超過(guò) 100 萬(wàn)的新 Series
:
population.apply(lambda val: val > 1000000)
0 False
1 True
2 False
dtype: bool
DataFrames 的修改方式也非常簡(jiǎn)單弱左。例如拆火,以下代碼向現(xiàn)有 DataFrame 添加了兩個(gè) Series:
cities['Area square miles'] = pd.Series([46.87, 176.53, 97.92])
cities['Population density'] = cities['Population'] / cities['Area square miles']
cities
City name Population Area square miles Population density
0 San Francisco 852469 46.87 18187.945381
1 San Jose 1015785 176.53 5754.177760
2 Sacramento 485199 97.92 4955.055147
練習(xí)1
通過(guò)添加一個(gè)新的布爾值列(當(dāng)且僅當(dāng)以下兩項(xiàng)均為 True 時(shí)為 True)修改 cities 表格:
- 城市以圣人命名优妙。
- 城市面積大于 50 平方英里套硼。
注意:布爾值 Series 是使用“按位”而非傳統(tǒng)布爾值“運(yùn)算符”組合的邪意。例如雾鬼,執(zhí)行邏輯與時(shí)策菜,應(yīng)使用 &又憨,而不是 and蠢莺。
提示:"San" 在西班牙語(yǔ)中意為 "saint"躏将。
解決方案:
cities['Is wide and has saint name'] = (cities['Area square miles'] > 50) & cities['City name'].apply(lambda name: name.startswith('San'))
City name Population Area square miles Population density Is wide and has saint name
0 San Francisco 852469 46.87 18187.945381 False
1 San Jose 1015785 176.53 5754.177760 True
2 Sacramento 485199 97.92 4955.055147 False
4.索引
Series 和 DataFrame 對(duì)象也定義了 index 屬性,該屬性會(huì)向每個(gè) Series 項(xiàng)或 DataFrame 行賦一個(gè)標(biāo)識(shí)符值夺衍。
默認(rèn)情況下沟沙,在構(gòu)造時(shí)矛紫,pandas 會(huì)賦可反映源數(shù)據(jù)順序的索引值颊咬。索引值在創(chuàng)建后是穩(wěn)定的喳篇;也就是說(shuō)麸澜,它們不會(huì)因?yàn)閿?shù)據(jù)重新排序而發(fā)生改變编矾。
案例1
city_names.index
RangeIndex(start=0, stop=3, step=1)
案例2
cities.index
RangeIndex(start=0, stop=3, step=1)
調(diào)用 DataFrame.reindex 以手動(dòng)重新排列各行的順序窄俏。例如凹蜈,以下方式與按城市名稱排序具有相同的效果:
cities.reindex([2, 0, 1])
City name Population Area square miles Population density Is wide and has saint name
2 Sacramento 485199 97.92 4955.055147 False
0 San Francisco 852469 46.87 18187.945381 False
1 San Jose 1015785 176.53 5754.177760 True
重建索引是一種隨機(jī)排列 DataFrame 的絕佳方式仰坦。在下面的示例中静尼,我們會(huì)取用類(lèi)似數(shù)組的索引鼠渺,然后將其傳遞至 NumPy 的 random.permutation 函數(shù)鹃祖,該函數(shù)會(huì)隨機(jī)排列其值的位置恬口。如果使用此重新隨機(jī)排列的數(shù)組調(diào)用 reindex歉秫,會(huì)導(dǎo)致 DataFrame 行以同樣的方式隨機(jī)排列雁芙。 嘗試多次運(yùn)行以下單元格!
cities.reindex(np.random.permutation(cities.index))
City name Population Area square miles Population density Is wide and has saint name
2 Sacramento 485199 97.92 4955.055147 False
0 San Francisco 852469 46.87 18187.945381 False
1 San Jose 1015785 176.53 5754.177760 True
City name Population Area square miles Population density Is wide and has saint name
1 San Jose 1015785 176.53 5754.177760 True
0 San Francisco 852469 46.87 18187.945381 False
2 Sacramento 485199 97.92 4955.055147 False
City name Population Area square miles Population density Is wide and has saint name
2 Sacramento 485199 97.92 4955.055147 False
1 San Jose 1015785 176.53 5754.177760 True
0 San Francisco 852469 46.87 18187.945381 False
練習(xí) 2
reindex 方法允許使用未包含在原始 DataFrame 索引值中的索引值。請(qǐng)?jiān)囈幌拢纯慈绻褂么祟?lèi)值會(huì)發(fā)生什么仙蛉!您認(rèn)為允許此類(lèi)值的原因是什么?
解決方案:
如果您的 reindex 輸入數(shù)組包含原始 DataFrame 索引值中沒(méi)有的值哀墓,reindex 會(huì)為此類(lèi)“丟失的”索引添加新行,并在所有對(duì)應(yīng)列中填充 NaN 值:
cities.reindex([0, 4, 5, 2])
City name Population Area square miles Population density Is wide and has saint name
0 San Francisco 852469.0 46.87 18187.945381 False
4 NaN NaN NaN NaN NaN
5 NaN NaN NaN NaN NaN
2 Sacramento 485199.0 97.92 4955.055147 False
這種行為是可取的,因?yàn)樗饕ǔJ菑膶?shí)際數(shù)據(jù)中提取的字符串(請(qǐng)參閱 pandas reindex 文檔贾漏,查看索引值是瀏覽器名稱的示例)。
在這種情況下伍掀,如果允許出現(xiàn)“丟失的”索引符匾,您將可以輕松使用外部列表重建索引啊胶,因?yàn)槟槐負(fù)?dān)心會(huì)將輸入清理掉聘惦。