Pandas操作
- pandas DataFrame
- pandas Series
pandas DataFrame
我們存儲數據最常用的形式是表格
- 表格就是由行和列所構成一種有序的組織形式
- 表格的第一行一般是變量名,也稱為表頭header
- 不同的變量可以是不同的數據類型
numpy array只能存儲一種數據類型,一個表格通常不僅僅只有數字類型。我們需要使用pandas包來處理
- pandas是數據科學中最常用的包之一,可以高效的處理各種數據
- pandas是基于numpy構建的
- pandas中重要的數據結構是series和DataFrame
# 導入pandas包
import pandas as pd
觀察數據常用方法
- df.head() 查看數據框df數據前幾行
- df.tail() 查看數據庫df數據后幾行
- df.info() 查看數據框df總體信息
- df.describe() 查看數據框df的各項統計信息
- df.index 查看數據框df的行索引
- df.columns 查看數據框的列名
- df.shape 查看數據框的形狀,行和列
Series數據的一些統計分析函數
- se.unique() 獲取series數據中的數值種類
- se.value_counts() 統計series數據中的數據種類以及對應數據的個數
- se.mean() 計算series數據的均值
- se.std() 計算series數據的標準差
- se.median()計算series數據的中位數
- se.max() 計算series數據的最大值
- se.min() 計算series數據的最小值
- se.count() 計算series數據的個數
pandas 繪圖函數
- df.plot(kind='scatter',x=,y=) 散點圖
- df.plot(kind = 'box') 箱圖
- df.boxplot(by='column_name') 箱圖,并按 column_name 分組
從字典創建一個DataFrame
gdp = {"country":["United States", "China", "Japan", "Germany", "United Kingdom"],
"capital":["Washington, D.C.", "Beijing", "Tokyo", "Berlin", "London"],
"population":[323, 1389, 127, 83, 66],
"gdp":[19.42, 11.8, 4.84, 3.42, 2.5],
"continent":["North America", "Asia", "Asia", "Europe", "Europe"]}
# 使用字典創建DataFrame,key將作為表頭
gdp_df = pd.DataFrame(gdp)
gdp_df#列索引是第一行 行索引是0-4
image.png
# 我們可以使用index選項來添加自定義的行標簽
# 使用column選項可以選擇列的順序
gdp_df = pd.DataFrame(gdp,columns=['country','capital','population','gdp','continent'],index = ['us','cn','jp','de','uk'])
gdp_df
gdp_df = pd.DataFrame(gdp,columns=gdp.keys(),index = ['us','cn','jp','de','uk'])
gdp_df
image.png
修改行和列的標簽
可以直接使用index和columns直接修改
gdp_df.index = ["US", "CN", "JP", "DE", "UK"]
gdp_df.columns = ["Country", "Capital", "Population", "GDP", "Continent"]
gdp_df
image.png
增加一列數據
# 增加rank列,表示他們的GDP處在前5位
gdp_df['rank'] = 'TOP5 GDP'
# 增加國土面積變量,以百萬公里計(數據來源:http://data.worldbank.org/)
gdp_df['Area'] = [9.15, 9.38, 0.37, 0.35, 0.24]
gdp_df
image.png
pandas series
- pandas中的series對象是另一個重要的數據結構
- 可以將其視為一個一維的DataFrame或者一個一維數組array加上一個索引index
- series的作用之一就是數據過濾和分組
# 一個最簡單series
series = pd.Series([2,4,5,7,3],index=['a','b','c','d','e'])
series
a 2
b 4
c 5
d 7
e 3
dtype: int64
# 當我們使用點操作符來查看一個變量時,返回的是一個series
gdp_df.GDP#US...UK是索引
US 19.42
CN 11.80
JP 4.84
DE 3.42
UK 2.50
Name: GDP, dtype: float64
# 可以直接查看索引
gdp_df.GDP.index
Index(['US', 'CN', 'JP', 'DE', 'UK'], dtype='object')
gdp_df.GDP > 4 #返回一個bool型的series 索引不參與運算
US True
CN True
JP True
DE False
UK False
Name: GDP, dtype: bool
我們也可以將series視為一個長度固定且有順序的字典,一些用于字典的函數也可以用于series
gdp_dict = {"US": 19.42, "CN": 11.80, "JP": 4.84, "DE": 3.42, "UK": 2.5}
gdp_series = pd.Series(gdp_dict)
gdp_series
CN 11.80
DE 3.42
JP 4.84
UK 2.50
US 19.42
dtype: float64
# 判斷us標簽是否在序列中
'US' in gdp_series
True
數據的選擇
- 可以使用[]來選擇所需要的列,里面那個括號可以傳入列索引或者列索引組成的列表 如果是列表則產生DataFrame 如果只是列索引則產生series
- 也可以使用點語法獲取某一列
- 使用[]切片 來選擇需要的行
- 使用loc和iloc方法選擇行和列
- 使用bool索引篩選數據
# 通過列索引選擇一列
gdp_df['Country']
US United States
CN China
JP Japan
DE Germany
UK United Kingdom
Name: Country, dtype: object
- 選擇列
# 同時選取多列
gdp_df[['Country','GDP']]
image.png
# 使用點語法獲取某一列 得到的也是series
gdp_df.GDP
US 19.42
CN 11.80
JP 4.84
DE 3.42
UK 2.50
Name: GDP, dtype: float64
- 選擇行
# 行選擇和2d數組選擇類似
gdp_df[2:5]
image.png
# loc方法是基于行標簽和列標簽的選取數據的方法
# 可以選取特定的行或列 也可以同時指定需要的行和列
# 和二維的numpy array的格式非常類似
# 第一個參數是行標簽,第二個參數是列標簽
gdp_df.loc[['JP','DE']]
image.png
# 以上例子選取了所有的列,我們可以篩選所需要的列
gdp_df.loc[['JP','DE'],['Country','GDP','Continent']]
image.png
# 選取所有的行,我們可以使用:表示選取所有的行
gdp_df.loc[:,['Country','GDP','Continent']]
image.png
# iloc方法 和 loc方法類似,但是是使用行列索引進行的數據篩選而不是用標簽
gdp_df.iloc[[2,3]] #等價于gdp_df.loc[['JP','DE']]
image.png
gdp_df.loc[["JP","DE"],["Country", "GDP", "Continent"]]
gdp_df.iloc[[2,3],[0,3,4]]
image.png
# 等價于gdp_df.loc[:, ["country", "GDP", "continent"]]
gdp_df.iloc[:, [0,3,4]]
image.png
使用布爾索引篩選數據
- 可以使用pandas series 來獲取一個 Boolean series
- 布爾索引的使用和numpy的array類似
- 可以結合[]或loc一起使用
# 使用bool索引篩選數據
# 選出亞洲國家 和下面的命令產生的結果是一樣的
gdp_df[gdp_df.Continent == 'Asia']
image.png
gdp_df.loc[gdp_df.Continent == 'Asia']
image.png
# 選出gdp大于3兆億美元的歐洲國家
gdp_df[(gdp_df.GDP>3) & (gdp_df.Continent == 'Europe')]
image.png
# 選出亞洲或者北美洲的國家記錄
gdp_df[(gdp_df.Continent=='Asia') | (gdp_df.Continent == 'North America')]
image.png
# 或者使用isin
gdp_df[gdp_df.Continent.isin(['Asia','North America'])]
image.png
數據的導入和觀察
# 用列表來存儲列標簽
col_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species']
# 讀取數據,并指定列標簽
iris = pd.read_csv('iris.txt',names=col_names)
# 讀取到的iris是DataFrame數據類型
# 使用head和tail查看頭尾
print(iris.head(10))
print(iris.tail(10))
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 Iris-setosa
1 4.9 3.0 1.4 0.2 Iris-setosa
2 4.7 3.2 1.3 0.2 Iris-setosa
3 4.6 3.1 1.5 0.2 Iris-setosa
4 5.0 3.6 1.4 0.2 Iris-setosa
5 5.4 3.9 1.7 0.4 Iris-setosa
6 4.6 3.4 1.4 0.3 Iris-setosa
7 5.0 3.4 1.5 0.2 Iris-setosa
8 4.4 2.9 1.4 0.2 Iris-setosa
9 4.9 3.1 1.5 0.1 Iris-setosa
sepal_length sepal_width petal_length petal_width species
140 6.7 3.1 5.6 2.4 Iris-virginica
141 6.9 3.1 5.1 2.3 Iris-virginica
142 5.8 2.7 5.1 1.9 Iris-virginica
143 6.8 3.2 5.9 2.3 Iris-virginica
144 6.7 3.3 5.7 2.5 Iris-virginica
145 6.7 3.0 5.2 2.3 Iris-virginica
146 6.3 2.5 5.0 1.9 Iris-virginica
147 6.5 3.0 5.2 2.0 Iris-virginica
148 6.2 3.4 5.4 2.3 Iris-virginica
149 5.9 3.0 5.1 1.8 Iris-virginica
# 使用info方法查看數據的總體信息
iris.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 5 columns):
sepal_length 150 non-null float64
sepal_width 150 non-null float64
petal_length 150 non-null float64
petal_width 150 non-null float64
species 150 non-null object
dtypes: float64(4), object(1)
memory usage: 5.9+ KB
# 使用shape可以查看DataFrame的行數和列數
iris.shape
(150, 5)
# 這是的species是分類變量,可以使用unique方法來查看品種的名字
iris.species.unique()
array(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'], dtype=object)
# 統計不同品種的數量
iris.species.value_counts()
Iris-setosa 50
Iris-versicolor 50
Iris-virginica 50
Name: species, dtype: int64
關于變量的種類
- 第一類是數量型(quantitative)變量,其中又可以進一步分為兩種
- 連續型的(continuous),比如一個人的身高和體重,當天的溫度等等。
- 離散型的(discrete),比如一個醫院醫生的人數,每天航班的次數等等。
- 第二類變量是性質型(qualitative)變量,也稱為分類變量(categorical)其中也可以進一步分為兩類
- 無序型變量,比如人的性別,上面列子中鳶尾花的品種。
- 有序型(ordinal),比如人的教育(本科,碩士,博士),收入分組(低,中,高收入)。
# 數據選擇復習
# 選取花瓣數據,即 petal_length 和 petal_width 這兩列
# 方法1 使用[[]]
petal = iris[['petal_length','petal_width']]
petal.head()
image.png
# 方法2 使用loc
petal = iris.loc[:,['petal_length','petal_width']]
petal.head()
image.png
# 方法3 使用iloc
petal = iris.iloc[:,2:4]
petal.head()
image.png
# 選取行索引為5-10的數據行
# 方法1 []切片
iris[5:11]
image.png
# 方法2 iloc
iris.iloc[5:11,:]
image.png
# 選取品種為 Iris-versicolor 的數據
versicolor = iris[iris.species == 'Iris-versicolor']
versicolor.head()
image.png
數據可視化初探
# 設置在notebook中直接展示圖形輸出
# 注意DataFrame也是基于matplotlib作圖的
%matplotlib inline
# 設置圖片清晰度
%config InlineBackend.figure_format = 'retina'
散點圖
# 我們首先畫散點圖(sactter plot),x軸上畫出花瓣的長度,y軸上畫出花瓣的寬度
iris.plot(kind='scatter',x='petal_length',y='petal_width')
<matplotlib.axes._subplots.AxesSubplot at 0x10ef71048>
image.png
# ?iris.plot 查看使用幫助
# 使用bool索引獲取三個品種的數據
setosa = iris[iris.species == 'Iris-setosa']
versicolor = iris[iris.species == 'Iris-versicolor']
virginica = iris[iris.species == 'Iris-virginica']
# 畫圖
ax = setosa.plot(kind='scatter', x="petal_length", y="petal_width", color='red',figsize=(10,6),label='setosa')
versicolor.plot(kind='scatter', x="petal_length", y="petal_width", color='Green', ax=ax, label='versicolor')
virginica.plot(kind='scatter', x="petal_length", y="petal_width", color='Orange', ax=ax, label='virginica')
<matplotlib.axes._subplots.AxesSubplot at 0x10e98fda0>
image.png
箱圖
# 使用mean方法獲取花瓣寬度均值
iris.petal_width.mean()
1.1986666666666672
# 使用median方法獲取花瓣寬度中位數
iris.petal_width.median()
1.3
# 使用describe方法來總結變量值
iris.describe()
iris.petal_width.describe()
count 150.000000
mean 1.198667
std 0.763161
min 0.100000
25% 0.300000
50% 1.300000
75% 1.800000
max 2.500000
Name: petal_width, dtype: float64
# 繪制花瓣寬度的箱圖
# 箱圖展示了數據中的中位數,四分位數,最大值,最小值
iris.petal_width.plot(kind='box')
<matplotlib.axes._subplots.AxesSubplot at 0x10f23eac8>
image.png
# 按品種分類,分別繪制不同品種花瓣寬度的箱圖
iris[['petal_width','species']].boxplot(by='species',grid=False,figsize=(10,6))
<matplotlib.axes._subplots.AxesSubplot at 0x11374bda0>
image.png