Matplotlib基礎04:使用Pandas繪製鳶尾花數據集

Matplotlib基礎04:使用Pandas繪製鳶尾花數據集

pandas模塊簡介

  1. Pandas模塊是Python用於數據導入及整理的模塊,對數據挖掘前期數據的處理工作十分有用。
  2. Pandas模塊的數據結構主要有兩:1、Series ;2、DataFrame
  3. 相比較於Numpy,Pandas可以存儲混合的數據結構,同時使用NaN來表示缺失的數據,而不用像Numpy一樣要手工處理缺失的數據,並且Pandas使用軸標籤來表示行和列。
  4. DataFrame:一個表格型的數據結構,包含有一組有序的列,每列可以是不同的值類型(數值、字符串、布爾型等),DataFrame即有行索引也有列索引,可以被看做是由Series組成的字典。DataFrame有四個重要的屬性:
    index:行索引。
    columns:列索引。
    values:值的二維數組。
    name:名字。
  5. Series結構是基於NumPy的ndarray結構,是一個一維的標籤矩陣(感覺跟python裏的字典結構有點像)

1. Series模塊:

import pandas as pd 
import numpy as np  

print("######################創建一個series##########################################")

#1.參數是list,index可以不指定,默認0,1,2
series = pd.Series([1,2,3,4],index=['a','b','c','d'])
print(series)
#2.參數是字典
dict = {'a':1,'b':2,"c":3,'d':4}
series = pd.Series(dict)
print(series)

print("################類似於np數組,可以進行切片,取值,加減法等##############################")
v = np.random.uniform(0,1,size=50)
series = pd.Series(v)
#打印指定索引的數字,同時可以輸出索引的
print(series[[3,34,25]])
#只輸出對應的數,不用輸出索引
print(series[3],series[34],series[25])
#切片形式,會輸出索引
print(series[1:6],"切片形式,會輸出索引")
#加減乘法,是相同的索引就進行運算,索引非兩者共有,則爲NaN
s1 = pd.Series([1,2,3,4],index=[1,2,3,4])
s2 = pd.Series([0,0,0,0],index=[2,3,4,5])
print(s1+s2,"加減乘法,是相同的索引就進行運算,索引非兩者共有,則爲NaN")
#取索引或者list
print(series.index)
print(series.values)

print("############################header與tail###############################################")
#s.head(n);.tail(n)//取出頭n行或尾n行,n爲可選參數,若不填默認5
s = pd.Series(v)
print(s.head())
print(s.tail(3))
print("------------------Series的屬性-------------------")
print("len():",len(s))#Series長度,包括NaN
print ("shape():",np.shape(s))#矩陣形狀,(,)
print ("count():",s.count())#Series長度,不包括NaN
print("unique():",s.unique()) #出現不重複values值
print ("value_counts():\n",s.value_counts())#統計每個value值出現次數

運行結果

PS E:\Anaconda-Vs-code> & C:/Users/86158/Anaconda3/envs/tensorflow/python.exe e:/Anaconda-Vs-code/第六講Matplotlib/matplotlib基礎03pandas.py/panda基本語法.py
######################創建一個series##########################################
a    1
b    2
c    3
d    4
dtype: int64
a    1
b    2
c    3
d    4
dtype: int64
################類似於np數組,可以進行切片,取值,加減法等##############################
3     0.415582
34    0.458589
25    0.975200
dtype: float64
0.41558192801102845 0.4585887695625541 0.9751998285422367
1    0.836265
2    0.675382
3    0.415582
4    0.656184
5    0.440431
dtype: float64 切片形式,會輸出索引
1    NaN
2    2.0
3    3.0
4    4.0
5    NaN
dtype: float64 加減乘法,是相同的索引就進行運算,索引非兩者共有,則爲NaN
RangeIndex(start=0, stop=50, step=1)
[0.67765165 0.83626514 0.67538175 0.41558193 0.65618418 0.44043073
 0.37757155 0.21390985 0.30330874 0.62883411 0.46198418 0.69404797
 0.10995785 0.02885739 0.613955   0.58406923 0.02610615 0.84504904
 0.17421594 0.459956   0.66605335 0.09834195 0.10498337 0.67250842
 0.21729545 0.97519983 0.68814137 0.16144825 0.56027213 0.57316921
 0.41345705 0.0897135  0.6374946  0.04959282 0.45858877 0.01610472
 0.58665787 0.50637486 0.31117577 0.59124138 0.38645648 0.33386051
 0.1943533  0.85668243 0.41325846 0.33481518 0.11426562 0.55620363
 0.71096422 0.52368542]
############################header與tail###############################################
0    0.677652
1    0.836265
2    0.675382
3    0.415582
4    0.656184
dtype: float64
47    0.556204
48    0.710964
49    0.523685
dtype: float64
------------------Series的屬性-------------------
len(): 50
shape(): (50,)
count(): 50
unique(): [0.67765165 0.83626514 0.67538175 0.41558193 0.65618418 0.44043073
 0.37757155 0.21390985 0.30330874 0.62883411 0.46198418 0.69404797
 0.10995785 0.02885739 0.613955   0.58406923 0.02610615 0.84504904
 0.17421594 0.459956   0.66605335 0.09834195 0.10498337 0.67250842
 0.21729545 0.97519983 0.68814137 0.16144825 0.56027213 0.57316921
 0.41345705 0.0897135  0.6374946  0.04959282 0.45858877 0.01610472
 0.58665787 0.50637486 0.31117577 0.59124138 0.38645648 0.33386051
 0.1943533  0.85668243 0.41325846 0.33481518 0.11426562 0.55620363
 0.71096422 0.52368542]
value_counts():
 0.334815    1
0.311176    1
0.677652    1
0.666053    1
0.856682    1
0.413258    1
0.333861    1
0.104983    1
0.213910    1
0.584069    1
0.556204    1
0.161448    1
0.303309    1
0.523685    1
0.688141    1
0.586658    1
0.377572    1
0.694048    1
0.675382    1
0.459956    1
0.710964    1
0.026106    1
0.461984    1
0.415582    1
0.413457    1
0.089713    1
0.028857    1
0.194353    1
0.098342    1
0.591241    1
0.217295    1
0.386456    1
0.458589    1
0.845049    1
0.836265    1
0.109958    1
0.672508    1
0.613955    1
0.560272    1
0.656184    1
0.573169    1
0.049593    1
0.440431    1
0.628834    1
0.975200    1
0.174216    1
0.506375    1
0.114266    1
0.637495    1
0.016105    1
dtype: int64

2. DataFrame模塊:
DataFrame創建的兩種方式:
1. 通過二維數組創建
2. 通過字典的方式創建,此種方法創建同時還要注意:
字典中的value值只能是一維數組 或 單個的簡單數據類型,
如果是數組,要求所有數組長度一致,如果是單個數據,則會使每行添加相同數據。
創建

#方法1:二維數組
df1 = pd.DataFrame([['joe','jone','Amy'],
[21,22,23],['teacher','doctor','programmer']])
print(df1)
#方法2:使用字典,設置索引index,字典裏的key會變成列索引標籤,行索引是字典裏面value
df2 = pd.DataFrame({'name':['joe','jone','Amy'],
'sex':['men','men','gril'],
'job':['teacher','doctor','programmer'],
'age':[21,22,23]},
index = ['first','second','third'])
print(df2)

在這裏插入圖片描述
使用其索引對象
不管是Series還是DataFrame對象,都有索引對象。索引對象負責管理軸標籤和其它元數據(axes)通過索引可以從Series、DataFrame中獲取值或者對某個索引值進行重新賦值。Series或者DataFrame的自動對齊功能是通過索引實現的
如:
修改列

print(df2.values,"發現打印出來了value")
#打印行列數據
print(df2.index,"\n",df2.columns,"發現打印出來了行列的值")
#修改列,存在這樣的列就輸出,不存在就創建
print(df2['name'],'發現打印出name這一列的數據\n',df2['sex'],"發現打印出sex這一列數據")
df2['kind_not'] = ['no','yes','no']
print(df2)
#刪除使用pop
df2.pop("age")
print(df2)

在這裏插入圖片描述
修改行


print("------------行的獲取修改與列不同,python使用loc,lx,python3使用loc,iloc--------")
#打印第二行
print(df2.iloc[2])
#使用loc獲取指定行列的值
print(df2.loc['third','job']) #也可以使用df2.loc['third']['job']
print(df2.loc['third']['job'])
#刪除使用drop,如刪除第一行
df2 = df2.drop('second')
print(df2)

在這裏插入圖片描述

使用pandas與matplotlib繪製數據集

1 .關於鳶尾花數據集

在這裏插入圖片描述
在這裏插入圖片描述
數據集的下載
get_file()函數——下載數據集

tf.keras.utils.get_file(fname, origin, cache_dir)
"""
fname:下載後的文件名;
origin:文件的URL地址;
cache_dir:下載後文件的存儲位置。C:\Users\\Administrator\.keras\datasets
n 參數
n 返回值:下載後的文件在本地磁盤中的絕對路徑。
"""

若沒有該數據集會下載:
在這裏插入圖片描述
和我們瞭解的csv數據集一樣,打開,裏面是一堆數據
在這裏插入圖片描述

繪製數據集圖表

import pandas as pd 
import numpy as np  
import matplotlib
import tensorflow as tf
import matplotlib.pyplot as plt
TRAIN_URL = 'http://download.tensorflow.org/data/iris_training.csv'
#下載數據集
train_path = tf.keras.utils.get_file(TRAIN_URL.split('/')[-1],TRAIN_URL)

#設置觀察數據
COLUMN_NAMES = ['SepalLength','SepalWidth','PetalLength','Species']
#讀取數據集第一列作爲標籤
df_iris = pd.read_csv(train_path,names=COLUMN_NAMES,header=0)
#轉化爲numpy數組
iris = np.array(df_iris)

fig = plt.figure('iris data',figsize=(15,15))
fig.suptitle("Anderson's iris data set\n(Blue->Setosa | Red->Versioncolor | Green->Virginica)",fontsize=20)
for i in range(4):
    for j in range(4):
        plt.subplot(4,4,4*i+(j+1))
        if i==j:
            plt.text(0.3,0.4,COLUMN_NAMES[i],fontsize=15)
        else:
            plt.scatter(iris[:,j],iris[:,i],c=iris[:,3],cmap='brg')
        if i==0:
            plt.title(COLUMN_NAMES[j])
        if j==0:
            plt.ylabel(COLUMN_NAMES[i])
plt.tight_layout()
plt.show()

在這裏插入圖片描述

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