一、numpy
import numpy as np
1.numpy 數(shù)組 和 list 的區(qū)別
輸出方式不同
里面包含的元素類型
2.構(gòu)造并訪問二維數(shù)組
使用 索引/切片 訪問ndarray元素
切片 左閉右開
np.array(list)
3.快捷構(gòu)造高維數(shù)組
-
np.arange()
-
np.random.randn() - - - 服從標(biāo)準(zhǔn)正態(tài)分布- - - 數(shù)學(xué)期望 μ - - - 標(biāo)準(zhǔn)方差 s
使用matplotlib.pyplot模塊驗(yàn)證標(biāo)準(zhǔn)正態(tài)分布 -
np.random.randint(起始數(shù),終止數(shù)(行,列))
4.改變數(shù)組的形狀 幾行幾列 reshape
二、pandas
數(shù)據(jù)分析 - - - 數(shù)據(jù)清洗 - - - 控制過(guò)濾 - - - 異常值捕獲
map分組 聚合
import numpy as np
import pandas as pd
pandas善于處理二維數(shù)據(jù)
1.數(shù)據(jù)結(jié)構(gòu) Series 和 DataFrame
Series
series
類似于通過(guò)numpy產(chǎn)生的一維數(shù)據(jù),但series包含索引(可以自己定)
DataFrame
DataFrame
是一種二維表格數(shù)據(jù)結(jié)構(gòu)
創(chuàng)建方法:
-
通過(guò)列表創(chuàng)建
行索引是
index
,列索引是columns
先創(chuàng)建一個(gè)空的DataFrame,通過(guò)列表生成DataFrame
-
通過(guò)字典創(chuàng)建
簡(jiǎn)單創(chuàng)建
將字典鍵變成行索引 - - - from_dict - - - orient(朝向)或者使用 Tdata = {'a':[1,3,5],'b':[2,4,6]} pd.DataFrame(data = data) pd.DataFrame.from_dict(data,orient='index')
-
通過(guò)二維數(shù)組創(chuàng)建
np.arange(12) # array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
2.修改索引
set_index 把常規(guī)行變成索引列
不會(huì)修改原始數(shù)據(jù),若希望修改,使用 inplace=True
data.set_index(‘index’, inplace=True)
修改列名稱 rename
修改列名稱,使用columns - - - 行 index
使用字典來(lái)表達(dá)映射關(guān)系 - - - {原始數(shù)據(jù):新數(shù)據(jù)}
將行索引變成常規(guī)列 reset_index()
若想修改原始數(shù)據(jù) 使用reset_index(replace=True)
3.Excel或csv數(shù)據(jù)的讀取和寫入
pd.read_excel
(file_name, sheet_name=0, index_col=0)
從左到右,第一個(gè)sheet索引是0,該函數(shù)返回該頁(yè)內(nèi)容 - - - 會(huì)將第一行變?yōu)榱兴饕?- - - 行索引從0開始
index_col=0 :將第一列變成行索引
header=0:將第一行變成列索引 - - - header=[0,1] 將前兩行變成列索引
xxx.to_excel(file_name)
:將數(shù)據(jù)寫到新的Excel文件
pd.read_csv(file_name, sep=',')
:讀取csv文件,sep默認(rèn)逗號(hào)分隔
index_col - - - headerxxx.to_csv(file_name)
4.pandas數(shù)據(jù)的讀取和篩選
df = pd.DataFrame(data=[[1,2,3],[4,5,6],[7,8,9]],index=['r1','r2','r3'],columns=['c1','c2','c3'])
- 讀取 列 xxx[‘xxx’]
- 讀取 行 xx.loc[‘xxx’]
-
df.head()
默認(rèn)查看前5行,出入幾查看幾行 -
查看特殊的數(shù)據(jù) 按照特定條件篩選
5.數(shù)據(jù)整體情況查看
- df.shape - - - 查看數(shù)據(jù)有幾行幾列
- df.describe() - - - 查看一些統(tǒng)計(jì)指標(biāo) – 每一列的個(gè)數(shù) 均值 標(biāo)準(zhǔn)方差 最小值 最大值
- df.info() - - - 查看表格數(shù)據(jù)的信息 - - - 每一列的個(gè)數(shù) 是否有空值 每一列的類型
- df.value_counts() - - - df.loc[‘r2’].value_counts()
查看某行或某列有哪些數(shù)據(jù),以及這些次數(shù)出現(xiàn)的頻次
6.數(shù)據(jù)運(yùn)算
- 從已有的列,通過(guò)數(shù)據(jù)運(yùn)算創(chuàng)造一個(gè)新的列
- sum 求和 mean 均值 axis=0 is 列(默認(rèn)) axis=1 is 行
求列方向的聚合值
7.數(shù)據(jù)映射 map()
map()根據(jù)列對(duì)數(shù)據(jù)進(jìn)行映射
map是一個(gè)循環(huán)遍歷的過(guò)程
people = pd.DataFrame(data={
'身高':np.random.randint(130,180,10),
'age':np.random.randint(18,23,10)
})
def map_high(x):
if x >= 170:
return '高'
else:
return '低'
people['高/低'] = people['身高'].map(map_high)
8.空值的填充和查找
NaN空值·
寫入空值
填充空值 fillna()
表格數(shù)據(jù)如果顯示NaN,表示此處為空值fillna()
函數(shù),可以填充空值inplace=True
表示寫入到數(shù)據(jù)內(nèi)存
people.fillna(value=0, inplace=True)
將空值NaN使用value替換
查找空值 isnull()
是NaN,返回True - - - True is 1
不是返回False - - - False is 0
xxx.isnull().sum()
對(duì)布爾值進(jìn)行列方向的求和 - - - - 求出每一列空值的個(gè)數(shù)
三、matplotlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
1.折線圖 plt.plot()
color 線的顏色
linewidth 線的寬度 像素
linestyle 線的風(fēng)格
dashed 虛線 dashdot 虛線和點(diǎn) dotted 點(diǎn)
# 可以省略,但建議寫上,強(qiáng)制將前面的繪圖代碼渲染出來(lái)
plt.show()
x = [1,2,3]
y = [2,4,6]
plt.plot(x,y)
a = [1,3,5]
b = [1,2,3]
plt.plot(a,b)
# 可以省略,但建議寫上,強(qiáng)制將前面的繪圖代碼渲染出來(lái)
plt.show()
2.柱狀圖 plt.bar()
條形圖的橫軸可以是字符串,起標(biāo)識(shí)作用
x = ['A','B','C','D']
y = [13,17,15,14]
# plt.bar(x,y, color=['red','blue'])
plt.bar(x,y,color=np.random.random((4,3)))
3.散點(diǎn)圖 plt.scatter()
回歸問題
# 橫軸數(shù)據(jù)
x = [1.3, 4,5.8,7.4]
# 縱軸數(shù)據(jù)
y = [20,30,40,50]
# 大小 也可以表達(dá)第三維數(shù)據(jù)
size = np.array([1,4,9,16])
plt.scatter(x,y,s=size*10,c=(1,2,3,4))
四、pandas 自帶的繪圖函數(shù)
DataFrame
# 從10到100隨機(jī)生成一個(gè)數(shù)據(jù)
np.random.randint(10,100) # 74
# 10行3列
np.random.randint(10,100,size=(10,3))
df = pd.DataFrame(data=np.random.randint(10,100, size=(10,3)),columns=['A','B','C'])
df.plot(kind='bar')
kind默認(rèn)是line
hist 直方圖 - - - pie 餅圖 - - - box 箱體圖 - - - area 面積圖
T轉(zhuǎn)置操作
Series
df = pd.Series(data=np.random.randint(1,10,size=5),index=['A','B','C','D','E'])
df.plot(kind='bar',color='red')
1.添加文字說(shuō)明 標(biāo)題 坐標(biāo)軸
np.random.random(3)
# array([0.62461037, 0.88015921, 0.78706271])
# 從0到2π拆分成100個(gè)數(shù),等差數(shù)列
x = np.linspace(0,2*np.pi, num=100)
y = np.sin(x)
# label 是圖例要展示的內(nèi)容
plt.plot(x,y,color=np.random.random(3),label='line of sin',linestyle='--')
# 允許展示圖例 loc參數(shù)可選
plt.legend(loc='lower right')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Y=sinX')
plt.plot(x,np.sin(x),label='sin')
plt.plot(x,np.cos(x),label='cos')
plt.legend(loc='upper right')
2.label中文報(bào)錯(cuò)解決方法
使用matplotlib畫圖,默認(rèn)不支持中文顯示
plt.rcParams # 可以查看一些默認(rèn)屬性
plt.rcParams['font.sans-serif']='SimHei' # 用來(lái)正常顯示中文標(biāo)簽
plt.rcParams['axes.unicode_minus']=False # 解決符號(hào)'-'顯示為方框的問題
plt.plot(x,np.sin(x),label='正弦函數(shù)')
plt.plot(x,np.cos(x),label='余弦函數(shù)')
plt.legend(loc='upper right')
plt.title('函數(shù)')
五、繪制多個(gè)圖表 subplot()
三個(gè)參數(shù)
plt.subplot(221) 兩行兩列第一個(gè)文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-693765.html
# 調(diào)整圖表大小
plt.figure(figsize=(12,8))
ax1 = plt.subplot(221)
ax1.plot(x,np.sin(x))
ax2 = plt.subplot(222)
ax2.plot(x,np.cos(x))
ax3 = plt.subplot(223)
ax3.bar(['a','b','c'],[1,2,3])
ax4 = plt.subplot(224)
# ax4.pie(sizes=[30,40,30],labels=['A','B','C'],colors=['red','blue','yellow'])
ax4.pie(np.array([10, 20, 30, 40]))
plt.show()
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-693765.html
到了這里,關(guān)于python-數(shù)據(jù)分析-numpy、pandas、matplotlib的常用方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!