python pandas numpy matplotlib 常用方法及函數


python pandas numpy matplotlib 常用方法及函數

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

---------------numpy-----------------------

arr = np.array([1,2,3], dtype=np.float64)

np.zeros((3,6))  np.empty((2,3,2)) np.arange(15)

arr.dtype arr.ndim arr.shape

arr.astype(np.int32) #np.float64 np.string_ np.unicode_

arr * arr arr - arr 1/arr

arr= np.arange(32).reshape((8,4))

arr[1:3, : ]  #正常切片

arr[[1,2,3]]  #花式索引

arr.T   arr.transpose((...))   arr.swapaxes(...) #轉置

arr.dot #矩陣內積

np.sqrt(arr)   np.exp(arr)    randn(8)#正態分布值   np.maximum(x,y)

np.where(cond, xarr, yarr)  #當cond為真,取xarr,否則取yarr

arr.mean()  arr.mean(axis=1)   算術平均數

arr.sum()   arr.std()  arr.var()   和、標准差、方差

arr.min()   arr.max()   最小值、最大值

arr.argmin()   arr.argmax()    #最小索引、最大索引

arr.cumsum()    arr.cumprod()   #所有元素的累計和、累計積

arr.all()   arr.any()   # 檢查數組中是否全為真、部分為真

arr.sort()   arr.sort(1)   #排序、1軸向上排序

arr.unique()   #去重

np.in1d(arr1, arr2)  #arr1的值是否在arr2中

np.load() np.loadtxt() np.save() np.savez() #讀取、保存文件

np.concatenate([arr, arr], axis=1)  #連接兩個arr,按行的方向

---------------pandas-----------------------

ser = Series()  

ser = Series([...], index=[...])  #一維數組, 字典可以直接轉化為series

ser.values  數組的值 

ser.index   數組的索引

ser.reindex([...], fill_value=0) 重新定義索引

ser.isnull()   pd.isnull(ser)   pd.notnull(ser)   #檢測缺失數據

ser.name=    ser本身的名字

ser.index.name=    ser索引的名字

ser.drop('x') #丟棄索引x對應的值

ser +ser  #算術運算

ser.sort_index()  按索引排序

ser.order()     按值排序

df = DataFrame(data, columns=[...], index=[...]) #表結構的數據結構,既有行索引又有列索引

df.ix['x']  #索引為x的值    對於series,直接使用ser['x']

del df['ly']  #用del刪除第ly列

df.T    #轉置

df.index.name df.columns.name df.values

df.drop([...])

df + df   df1.add(df2, fill_vaule=0) #算術運算

df -ser   #df與ser的算術運算

f=lambda x: x.max()-x.min()   

df.apply(f)

df.sort_index(axis=1, ascending=False)   按行索引排序

df.sort_index(by=['a','b'])   按a、b列索引排序

ser.rank()   df.rank(axis=1)  #排序,增設一個排名值

df.sum()   df.sum(axis=1)   #按列、按行求和

df.mean(axis=1, skipna=False)   #求各行的平均值,考慮na的存在

df.idxmax()   #返回最大值的索引

df.cumsum()   #累計求和

df.describe()  ser.describe()   返回count

mean std min max等值

ser.unique()  #去重

ser.value_counts()   df.value_counts()  返回一個series,其索引為唯一值,值為頻率

ser.isin(['x', 'y'])  #判斷ser的值是否為x,y,得到布爾值

ser.dropna() ser.isnull() ser.notnull() ser.fillna(0)  #處理缺失數據,df相同

df.unstack()   #行列索引和值互換  df.unstack().stack()

df.swaplevel('key1','key2')   #接受兩個級別編號或名稱,並互換

df.sortlevel(1) #根據級別1進行排序,df的行、列索引可以有兩級

df.set_index(['c','d'], drop=False)    #將c、d兩列轉換為行,因drop為false,在列中仍保留c,d

read_csv   read_table   read_fwf    讀取文件分隔符為逗號、分隔符為制表符('\t')、無分隔符(固定列寬)

pd.read_csv('...', nrows=5) 讀取文件前5行

pd.read_csv('...', chunksize=1000) 按塊讀取,避免過大的文件占用內存

pd.load() #pd也有load方法,用來讀取二進制文件

pd.ExcelFile('...xls').parse('Sheet1')  讀取excel文件中的sheet1

df.to_csv('...csv', sep='|', index=False, header=False) #將數據寫入csv文件,以|為分隔符,默認以,為分隔符, 禁用列、行的標簽

pd.merge(df1,

df2, on='key', suffixes=('_left', '_right')) #合並兩個數據集,類似數據庫的inner join,

以二者共有的key列作為鍵,suffixes將兩個key分別命名為key_left、key_right

pd.merge(df1, df2, left_on='lkey', right_on='rkey') #合並,類似數據庫的inner join, 但二者沒有同樣的列名,分別指出,作為合並的參照

pd.merge(df1, df2, how='outer') #合並,但是是outer join;how='left'是笛卡爾積,how='inner'是...;還可以對多個鍵進行合並

df1.join(df2, on='key', how='outer')  #也是合並

pd.concat([ser1, ser2, ser3], axis=1) #連接三個序列,按行的方向

ser1.combine_first(ser2)   df1.combine_first(df2) #把2合並到1上,並對齊

df.stack() df.unstack()  #列旋轉為行、行旋轉為列

df.pivot()

df.duplicated()   df.drop_duplicates() #判斷是否為重復數據、刪除重復數據

df[''].map(lambda x: abs(x)) #將函數映射到df的指定列

ser.replace(-999, np.nan) #將-999全部替換為nan

df.rename(index={}, columns={}, inplace=True) #修改索引,inplace為真表示就地修改數據集

pd.cut(ser, bins)  #根據面元bin判斷ser的各個數據屬於哪一個區段,有labels、levels屬性

df[(np.abs(df)>3).any(1)] #輸出含有“超過3或-3的值”的行

permutation  take    #用來進行隨機重排序

pd.get_dummies(df['key'], prefix='key')  #給df的所有列索引加前綴key

df[...].str.contains()  df[...].str.findall(pattern,

flags=re.IGNORECASE)  df[...].str.match(pattern,

flags=...)    df[...].str.get()  #矢量化的字符串函數

一、選取標簽為A和C的列,並且選完類型還是dataframe

df = df.loc[:, ['A','C']]

df = df.iloc[:,

[0,2]]

二、選取標簽為C並且只取前兩行,選完類型還是dataframe

df = df.loc[0:2, ['A','C']]

df = df.iloc[0:2, [0,2]]

----繪圖

ser.plot() df.plot() #pandas的繪圖工具,有參數label, ax, style, alpha, kind, logy, use_index, rot, xticks, xlim, grid等,詳見page257

kind='kde' #密度圖

kind='bar' kind='barh' #垂直柱狀圖、水平柱狀圖,stacked=True為堆積圖

ser.hist(bins=50) #直方圖

plt.scatter(x,y) #繪制x,y組成的散點圖

pd.scatter_matrix(df, diagonal='kde', color='k', alpha='0.3')  #將df各列分別組合繪制散點圖

----聚合分組

groupby() 默認在axis=0軸上分組,也可以在1組上分組;可以用for進行分組迭代

df.groupby(df['key1'])根據key1對df進行分組

df['key2'].groupby(df['key1'])  #根據key1對key2列進行分組

df['key3'].groupby(df['key1'], df['key2'])  #先根據key1、再根據key2對key3列進行分組

df['key2'].groupby(df['key1']).size() #size()返回一個含有分組大小的series

df.groupby(df['key1'])['data1']  等價於

df['data1'].groupby(df['key1'])

df.groupby(df['key1'])[['data1']]  等價於  df[['data1']].groupby(df['key1'])

df.groupby(mapping, axis=1)  ser(mapping) #定義mapping字典,根據字典的分組來進行分組

df.groupby(len) #通過函數來進行分組,如根據len函數

df.groupby(level='...', axis=1)  #根據索引級別來分組

df.groupby([], as_index=False)   #禁用索引,返回無索引形式的數據

df.groupby(...).agg(['mean', 'std'])   #一次使用多個聚合函數時,用agg方法

df.groupby(...).transform(np.mean)   #transform()可以將其內的函數用於各個分組

df.groupby().apply()  apply方法會將待處理的對象拆分成多個片段,然后對各片段調用傳入的函數,最后嘗試將各片段組合到一起

----透視交叉

df.pivot_table(['',''], rows=['',''], cols='', margins=True)  #margins為真時會加一列all

pd.crosstab(df.col1, df.col2, margins=True) #margins作用同上

---------------matplotlib---------------

fig=plt.figure() #圖像所在的基對象

ax=fig.add_subplot(2,2,1)  #2*2的圖像,當前選中第1個

fig, axes = plt.subplots(nrows, nclos, sharex, sharey)  #創建圖像,指定行、列、共享x軸刻度、共享y軸刻度

plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

#調整subplot之間的距離,wspace、hspace用來控制寬度、高度百分比

ax.plot(x, y, linestyle='--', color='g')   #依據x,y坐標畫圖,設置線型、顏色

ax.set_xticks([...]) ax.set_xticklabels([...]) #設置x軸刻度

ax.set_xlabel('...') #設置x軸名稱

ax.set_title('....') #設置圖名

ax.legend(loc='best') #設置圖例, loc指定將圖例放在合適的位置

ax.text(x,y, 'hello', family='monospace', fontsize=10) #將注釋hello放在x,y處,字體大小為10

ax.add_patch() #在圖中添加塊

plt.savefig('...png', dpi=400, bbox_inches='tight') #保存圖片,dpi為分辨率,bbox=tight表示將裁減空白部分

------------------------------------------

from mpl_toolkits.basemap import Basemap

import matplotlib.pyplot as plt

#可以用來繪制地圖

-----------------時間序列--------------------------

pd.to_datetime(datestrs)    #將字符串型日期解析為日期格式

pd.date_range('1/1/2000', periods=1000)    #生成時間序列

ts.resample('D', how='mean')   #采樣,將時間序列轉換成以每天為固定頻率的, 並計算均值;how='ohlc'是股票四個指數;

#重采樣會聚合,即將短頻率(日)變成長頻率(月),對應的值疊加;

#升采樣會插值,即將長頻率變為短頻率,中間產生新值

ts.shift(2, freq='D')   ts.shift(-2, freq='D') #后移、前移2天

now+Day() now+MonthEnd()

import pytz   pytz.timezone('US/Eastern')   #時區操作,需要安裝pytz

pd.Period('2010', freq='A-DEC')   #period表示時間區間,叫做時期

pd.PeriodIndex    #時期索引

ts.to_period('M')   #時間轉換為時期

pd.rolling_mean(...)    pd.rolling_std(...)   #移動窗口函數-平均值、標准差


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM