我的Python數據分析筆記之一


(聲明:本教程僅供本人學習使用,如有人使用該技術觸犯法律與本人無關)
(如果有錯誤,還希望指出。共同進步)


【注】【書籍在線地址】--------="" 這裏 “”=--------


數據

  • 分爲結構化數據和非結構化數據

結構化數據

  • 表格型數據,其中各列可能是不同的類型
  • 多維數組(矩陣)
  • 通過關鍵列相互聯繫的多個表,如SQL用戶來說,就是指主鍵和外鍵
  • 間隔平均或不平均的時間序列

非結構化數據

  • 文章,例如新聞文章可以被處理成詞頻錶轉化爲結構化數據
  • 一段文字
  • 總的來說就是:指沒有維度索引的數據集合(自己理解)

Python庫

  • Numpy
  • Pandas
  • Matplotlib
  • Scipy
  • Scikit-learn
  • statsmodels

[查看所擁有的方法] —— dir(object)


Numpy

導入

import numpy as np

創建ndarray

arr1 = np.array( parms:list )
  • parms參數介紹
  1. 列表
  2. 嵌套序列(比如由一組等長列表組成的列表),如[[1, 2, 3, 4], [5, 6, 7, 8]]

屬性

  • np.ndim: 查看維度
  • np.shape: 形狀(各維度的長度)
  • np.size: 總長度(元素的總個數)
  • np.dtype: 元素類型

方法

  • np.astype(<類型>): 將np對象轉換成指定的數據類型

    幾種常見的類型
    1、np.float64
    2、np.int32
    3、np.int64
    4、np.string_

 arr = np.array([1, 2, 3, 4, 5])
 float_arr = arr.astype(np.float64)
  • np.ones(shape, dtype=None, order=“C”): 數據全部爲1
ones = np.ones((400, 600, 3), dtype="float")
  • np.zeros(shape, dtype=None, order=“C”) : 數據全部爲0
  • np.arange([start, ]stop, [step, ]dtype=None): 創建從start開始到stop(不包括stop)結束,以step爲間隔的array對象,類型爲dtype
  • np.eye(5):對角線爲1其它的位置爲0 (5行5列)
  • np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) :start:開始,stop:結束;num等分成多少
  • np.random.randint(low, high=None, size=None, dtype=‘l’)
  • np.random.randn(d0, d1, …, dn) (基數爲0,方差爲1,)
  • np.random.normal(loc=0.0, scale=1.0, size=None): 僞隨機數生成(loc定義基數,scale定義方差)
  • np.random.random(size=None)
  • np.where(cond, xarr, yarr): 根據cond中的值選取xarr和yarr的值:當cond中的值爲True時,選取xarr的值,否則從yarr中選取
xarr = np.array([1.1, 1.2, 1.3, 1.4, 1.5])
yarr = np.array([2.1, 2.2, 2.3, 2.4, 2.5])
cond = np.array([True, False, True, True, False])

result = np.where(cond, xarr, yarr)
# 拓展
# np.where(arr > 0, 2, -2)
# np.where(arr > 0, 2, arr) 

result
# array([ 1.1,  2.2,  1.3,  1.4,  2.5])
  • np.sum(arr, axis=0|1) : 求和
  • arr.sum(axis=0|1)
  • np.mean(axi=0|1): 求平均值
  • np.cumsum(axis=0|1): 累加函數
  • np.save(‘some_array’, arr): 將arr數組以未壓縮的原始二進制格式保存在擴展名爲.npy的文件中,文件路徑末尾沒有擴展名.npy,則該擴展名會被自動加上
  • np.load(‘some_array.npy’):讀取磁盤上的數組
  • np.dot(x, y): 矩陣點乘
  • arr1 @ arr2: 矩陣點乘

Pandas

導入

import pandas as pd
from pandas import Series
from pandas import DataFrame
from pandas import Panel

Ndarray和DataFrame

在這裏插入圖片描述
【下標默認如同列表的數字下標】/【擁有行索引和列索引】


Numpy_Pandas : Series_DataFrame_Panel

在這裏插入圖片描述
【解釋】:np.narray對象中narray中的n指的是幾維,如下的1D_array指的是1維的narray對象。

  • Series = 1D_array + index
  • DataFrame = 2D_array + index + columns
  • Panel = 3D_array + index + columns + item

Series

是一種類似於一維數組的對象,它由一組數據(各種NumPy數據類型)以及一組與之相關的數據標籤(即索引)組成,類似於 python 中的基本數據的 list 或 NumPy 中的 1D array。Pandas 裏最基本的數據結構

字符串表現形式爲:索引在左邊,值在右邊。由於我們沒有爲數據指定索引,於是會自動創建一個0到N-1(N爲數據的長度)的整數型索引

創建

pd.Series( x, index=idx )

	X 是位置參數,指的是數據值,類型可以是:
	* 列表 (list)
	* numpy 數組 (1D_array)
	* 字典 (dict)X 參數詳解
	
	index是默認參數,設置的是數據下標參數,默認值:
	*  idx = range(0, len(x))

方法

ser = pd.Series([1, 2, 3, 4, 5, 6])
 * ser.value:  打印ser中的數據元素
 * ser.index:  打印ser中元素對應的索引
 * ser.name:  Series本身的name屬性
 * ser.index.name:  Series索引的name屬性
# 修改Series 的索引
ser.index = [1, 2, 3, 4, 5, 6]
# 修改 Series 的 name
ser.name = "測試用例"
# 修改 Series 的索引的 name
ser.index.name = "index_set"
 * len(ser) :  統計個數
 * ser.shape: 形狀(用元組表示)
 * ser.count():  ser中不含Nan的元素個數
 * ser.unique():  返回ser中不重複的元素
 * ser.value_counts(): 統計ser中非Nan元素的出現次數
ser + ser

# >>> ser + ser
# 1     2
# 2     4
# 3     6
# 4     8
# 5    10
# 6    12
# dtype: int32

DataFrame

是一個表格型的數據結構,它含有一組有序的列,每列可以是不同的值類型(數值、字符串、布爾值等)。DataFrame既有行索引也有列索引,它可以被看做由Series組成的字典(共用同一個索引)。DataFrame中的數據是以一個或多個二維塊存放的(而不是列表、字典或別的一維數據結構)。

二維數據,類似於 R 中的 data.frame 或 Matlab 中的 Tables。DataFrame 是 Series 的容器

最常見的數據類型是二維的 DataFrame,其中

	 - 每行代表一個示例 (instance)
	 
	 - 每列代表一個特徵 (feature)

DataFrame 可理解成是 Series 的容器,每一列都是一個 Series,或者 Series 是隻有一列的 DataFrame

創建

pd.DataFrame( x, index=idx, columns=col )

	X 是位置參數,指的是數據值,類型可以是:
	* 二維列表 (list)
	* 二維 numpy 數組 (3D_array)
	* 字典 (dict),其值是一維列表、numpy 數組或 Series
	* 另外一個 DataFrame
	
	index是默認參數,設置的是數據"行"下標參數,默認值:
	* idx = range(0, x.shape[0])
	
	columns是默認參數,設置的是數據"列"下標參數,默認值:
	* col = range(0, x.shape[1])

方法

data = {
	'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada', 'Nevada'],
	'year': [2000, 2001, 2002, 2001, 2002, 2003],
	'pop': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]
}
# 創建DataFrame對象
df2 = pd.DataFrame(data, columns=['year', 'state', 'pop', 'debt'], index=['one', 'two', 'three', 'four', 'five', 'six'])

       year   state  pop debt
one    2000    Ohio  1.5  NaN
two    2001    Ohio  1.7  NaN
three  2002    Ohio  3.6  NaN
four   2001  Nevada  2.4  NaN
five   2002  Nevada  2.9  NaN
six    2003  Nevada  3.2  NaN
 * del df2["debt"] : 刪除指定列
 * df2.head(n):查看前n行,默認是5行
 * df2.tail(n):查看後n行,默認是5行
 * df2.describe():統計數據
 * df2.groupby():分組統計數據與統計函數連用如sum、max、count等

Panel


【注】: Panel 支持python2, 不支持python3


Panel 可理解成是 DataFrame 的容器

創建

pd.Panel( x, item=itm, major_axis=n1,  minor_axis=n2 )

		其中 x 可以是

		* 三維列表 (list)
		* 三維 numpy 數組 (3D_array)
		* 字典 (dict),其值是 DataFrame


		x 是位置參數
		* items 是默認參數 (axis 0),默認值爲 itm = range(0, number of DataFrame)
		* major_axis 是默認參數 (axis 1),默認值和 DataFrame 的默認 index 一樣
		* minor_axis 是默認參數 (axis 2),默認值和 DataFrame 的默認 columns 一樣
pn = pd.Panel(np.random.randn(2, 5, 4))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章