第五節(jié) Pandas高級數(shù)據(jù)結構
一、 Pandas介紹與安裝
1.1 為什么會有Pandas?
Pandas支持大部分Numpy語言風格,尤其是數(shù)組函數(shù)與廣播機制的各種數(shù)據(jù)處理。但是Numpy更適合處理同質型的數(shù)據(jù)。而Pandas的設計就是用來處理表格型或異質型數(shù)據(jù)的,高效的清洗、處理數(shù)據(jù)。
1.2 Pandas是什么?
Pandas是基于Numpy的一種工具,提供了高性能矩陣的運算,該工具是為了解決數(shù)據(jù)分析任務而創(chuàng)建的。也是貫穿整個Python數(shù)據(jù)分析非常核心的工具。
1.3 Pandas涉及內容

1.4 Pandas安裝
直接在dos命令行中pip install pandas 即可。
二、 Pandas數(shù)據(jù)結構介紹
2.1 Series
2.1.1 Series介紹
Series是一種一維的數(shù)組型對象,它包含了一個值序列(values),并且包含了數(shù)據(jù)標簽,稱為索引(index)。
2.1.2 Series創(chuàng)建
- pd.Series(data=None,index=None,dtype=None,name=None,copy=False)
data:創(chuàng)建數(shù)組的數(shù)據(jù),可為array-like, dict, or scalar value
index:指定索引
dtype:數(shù)組數(shù)據(jù)類型
name:數(shù)組名稱
copy:是否拷貝
2.1.3 創(chuàng)建方式
-
通過列表創(chuàng)建 s = pd.Series([1,2,3])
image.png -
通過元組創(chuàng)建 s1 = pd.Series((1,2,3))
image.png -
通過數(shù)組創(chuàng)建
image.png -
通過字典創(chuàng)建
image.png
2.1.4 Series簡單使用
- series的索引與值



-
s.index 查看索引
image.png -
s.values 查看值序列
image.png
- s.reset_index(drop=False) 重置索引
drop # 是否刪除原索引 默認為否
注意:索引對象是不可變的,所以不能單個修改索引
-
切片:下標切片是左閉右開,標簽切片是包含右邊的標簽值
image.png
image.png Series索引與切片
s['標簽'] # 通過標簽
s['索引'] # 通過索引
s.loc(標簽) # 通過標簽
s.iloc(索引) # 通過索引Series簡單函數(shù)
s3.isnull() # 檢查缺失值
image.png
s.head(n) # 預覽數(shù)據(jù)前5條
image.png
s.dtype # 查看數(shù)據(jù)類型
s.astype() # 修改數(shù)據(jù)類型
image.png
s.tail(n) # 預覽數(shù)據(jù)后5條
image.png
2.2 DataFrame 表格型數(shù)據(jù)結構
2.2.1 DataFrame介紹
DataFrame表示的是矩陣的數(shù)據(jù)表,它包含已排序的列集合,每一列可以是不同的值類型(數(shù)值,字符串,布爾值)。在DataFrame中,數(shù)據(jù)被存儲為一個以上的二維塊。
2.2.2 DataFrame創(chuàng)建
pd.DataFrame(data=None,index=None,columns=None,dtype=None,copy=False)
data:創(chuàng)建數(shù)組的數(shù)據(jù),可為ndarray, dict
index:指定索引
dtype:數(shù)組數(shù)據(jù)類型
copy:是否拷貝
2.2.3 創(chuàng)建方式一: 字典類
-
數(shù)組,列表,或者元組構成的字典構造dataframe
image.png
index屬性:行索引,列索引
image.png
可以指定行索引和列索引
image.png -
series組成字典構造dataframe
image.png -
字典組成字典構造dataframe
image.png
2.2.4 創(chuàng)建方式二: 列表類
-
二維數(shù)組構造dataframe
image.png -
字典構造列表構造dataframe
image.png -
series組成的列表構造dataframe
image.png
2.2.5 補充創(chuàng)建描述

2.2.6 基本操作
-
索引查詢
image.png
image.png -
通過索引改行列、增行列數(shù)據(jù)
image.png
-
刪除行列
image.png 一般使用drop刪除行列,axis=0指定所在的行列,inplace是否有返回值,默認在原數(shù)據(jù)修改
























