[Python]Pandas簡單入門(轉)

本篇文章轉自 https://colab.research.google.com/notebooks/mlcc/intro_to_pandas.ipynb?hl=zh-cn#scrollTo=zCOn8ftSyddH

是Google的Machine Learning課程中關於Pandas的入門教程,感覺講的很簡單很實用,直接搬運過來

 

學習目標:

  • 大致瞭解 pandas 庫的 DataFrame 和 Series 數據結構
  • 存取和處理 DataFrame 和 Series 中的數據
  • 將 CSV 數據導入 pandas 庫的 DataFrame
  • 對 DataFrame 重建索引來隨機打亂數據
 

 

pandas 是一種列存數據分析 API。它是用於處理和分析輸入數據的強大工具,很多機器學習框架都支持將 pandas 數據結構作爲輸入。 雖然全方位介紹 pandas API 會佔據很長篇幅,但它的核心概念非常簡單,我們會在下文中進行說明。有關更完整的參考,請訪問 pandas 文檔網站,其中包含豐富的文檔和教程資源。

 

 

基本概念

以下行導入了 pandas API 並輸出了相應的 API 版本:

import pandas as pd
pd.__version__
 

 

pandas 中的主要數據結構被實現爲以下兩類:

  • DataFrame,您可以將它想象成一個關係型數據表格,其中包含多個行和已命名的列。
  • Series,它是單一列。DataFrame 中包含一個或多個 Series,每個 Series 均有一個名稱。

數據框架是用於數據操控的一種常用抽象實現形式。Spark 和 R 中也有類似的實現。


 
創建 Series 的一種方法是構建 Series 對象。例如: 
pd.Series(['San Francisco', 'San Jose', 'Sacramento'])
pd.Series(['San Francisco', 'San Jose', 'Sacramento'])
0 San Francisco
1 San Jose 2 Sacramento dtype: object

 

您可以將映射 string 列名稱的 dict 傳遞到它們各自的 Series,從而創建DataFrame對象。如果 Series 在長度上不一致,系統會用特殊的 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
 

 

但是在大多數情況下,您需要將整個文件加載到 DataFrame 中。下面的示例加載了一個包含加利福尼亞州住房數據的文件。請運行以下單元格以加載數據,並創建特徵定義:

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 來顯示關於 DataFrame 的有趣統計信息。另一個實用函數是 DataFrame.head,它顯示 DataFrame 的前幾個記錄:

 
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 的另一個強大功能是繪製圖表。例如,藉助 DataFrame.hist,您可以快速瞭解一個列中值的分佈:

 
california_housing_dataframe.hist('housing_median_age')

 


 

 

訪問數據

您可以使用熟悉的 Python dict/list 指令訪問 DataFrame 數據:

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
print type(cities['City name'][1])
cities['City name'][1]

<type 'str'>

'San Jose'
print type(cities[0:2])
cities[0:2]
<class 'pandas.core.frame.DataFrame'>
City name    Population    Area square miles    Population density
0    San Francisco    852469    46.87    18187.945381
1    San Jose    1015785    176.53    5754.177760
 

 

此外,pandas 針對高級索引和選擇提供了極其豐富的 API(數量過多,此處無法逐一列出)。

 

 

操控數據

您可以向 Series 應用 Python 的基本運算指令。例如:

population / 1000

0 852.469 
1 1015.785
2 485.199
dtype: float64
 

 

NumPy 是一種用於進行科學計算的常用工具包。pandas Series 可用作大多數 NumPy 函數的參數:

import numpy as np
np.log(population)

0    13.655892
1    13.831172
2    13.092314
dtype: float64

 


 

對於更復雜的單列轉換,您可以使用 Series.apply。像 Python 映射函數一樣,Series.apply 將以參數形式接受 lambda 函數,而該函數會應用於每個值。

下面的示例創建了一個指明 population 是否超過 100 萬的新 Series

population.apply(lambda val: val > 1000000)

0    False
1     True
2    False
dtype: bool
 

 

DataFrames 的修改方式也非常簡單。例如,以下代碼向現有 DataFrame 添加了兩個 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
 

 

練習 1

通過添加一個新的布爾值列(當且僅當以下兩項均爲 True 時爲 True)修改 cities 表格:

  • 城市以聖人命名。
  • 城市面積大於 50 平方英里。

注意:布爾值 Series 是使用“按位”而非傳統布爾值“運算符”組合的。例如,執行邏輯與時,應使用 &,而不是 and

提示:"San" 在西班牙語中意爲 "saint"。

 

 
 
cities['bool new'] = (cities['City name'].apply(lambda name: name.startswith('San')) & cities['Area square miles'] > 50 )
cities

  City name    Population    Area square miles    Population density    bool ly
0  San Francisco    852469        46.87        18187.945381        False    
1  San Jose       1015785        176.53       5754.177760         False
2  Sacramento      485199        97.92        4955.055147          False    

  


 

索引

Series 和 DataFrame 對象也定義了 index 屬性,該屬性會向每個 Series 項或 DataFrame 行賦一個標識符值。

默認情況下,在構造時,pandas 會賦可反映源數據順序的索引值。索引值在創建後是穩定的;也就是說,它們不會因爲數據重新排序而發生改變。

 

調用 DataFrame.reindex 以手動重新排列各行的順序。例如,以下方式與按城市名稱排序具有相同的效果:

 
cities.reindex([2, 0, 1])

  City name    Population    Area square miles    Population density   bool new
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        False

 

 

 

重建索引是一種隨機排列 DataFrame 的絕佳方式。在下面的示例中,我們會取用類似數組的索引,然後將其傳遞至 NumPy 的 random.permutation 函數,該函數會隨機排列其值的位置。如果使用此重新隨機排列的數組調用 reindex,會導致 DataFrame 行以同樣的方式隨機排列。 嘗試多次運行以下單元格!

 
cities.reindex(np.random.permutation(cities.index))

    City name    Population    Area square miles    Population density    bool ly
1    San Jose       1015785      176.53           5754.177760         False
0    San Francisco  852469       46.87            18187.945381        False
2    Sacramento     485199       97.92            4955.055147         False
 

 

如果您的 reindex 輸入數組包含原始 DataFrame 索引值中沒有的值,reindex 會爲此類“丟失的”索引添加新行,並在所有對應列中填充 NaN 值:

這種行爲是可取的,因爲索引通常是從實際數據中提取的字符串(請參閱 pandas reindex 文檔,查看索引值是瀏覽器名稱的示例)。

在這種情況下,如果允許出現“丟失的”索引,您將可以輕鬆使用外部列表重建索引,因爲您不必擔心會將輸入清理掉。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章