pandas的一些理解
pandas 簡介
numpy 能夠幫我們處理的是 數(shù)值型數(shù)據(jù),但是這還不夠,很多時候,我們的數(shù)據(jù)除了數(shù)值之外,還有字符串,還有時間序列等,
這是就需要 pandas 幫我們處理它們了。
什么是Pandas?
Pandas的名稱來自于面板數(shù)據(jù)(panel data)
Pandas是一個強大的分析結(jié)構(gòu)化數(shù)據(jù)的工具集,基于NumPy構(gòu)建,提供了高級數(shù)據(jù)結(jié)構(gòu)和數(shù)據(jù)操作工具,它是使Python成為強大而高效的數(shù)據(jù)分析環(huán)境的重要因素之一。
。一個強大的分析和操作大型結(jié)構(gòu)化數(shù)據(jù)集所需的工具集
。基礎(chǔ)是NumPy,提供了高性能矩陣的運算
。提供了大量能夠快速便捷地處理數(shù)據(jù)的函數(shù)和方法
。應(yīng)用于數(shù)據(jù)挖掘,數(shù)據(jù)分析
。提供數(shù)據(jù)清洗功能
pandas 的數(shù)據(jù)結(jié)構(gòu)
pandas 庫有兩個重要的數(shù)據(jù)結(jié)構(gòu):
我們可以將 Series 看作顯示了索引的一維數(shù)組,將 DataFrame 看作顯示了縱橫軸索引的二維數(shù)組,因此 numpy 的許多方法與函數(shù)可以用在 Series 與 DataFrame 上。
Series對象
我們首先來了解 Series ,因為 Pandas 是基于NumPy構(gòu)建的,所以我們可以參考 一維數(shù)組 對象來理解 Series對象。
import numpy as np import pandas as pd list_1=list(range(1,6)) arr=np.array(list_1) ser=pd.Series(list_1) print(f'這是由 1 到 5 構(gòu)成的一維數(shù)組,只有數(shù)據(jù)元素:\n{arr}') print(f'這是由 1 到 5 構(gòu)成的Series對象,由數(shù)據(jù)元素及其索引:\n{ser}')由此我們可以更好的理解 Ndarray 對象和 Series 對象,
Series 對象的創(chuàng)建:
pandas. Series ( data , index , dtype , name , copy )
Series . name=str 設(shè)置元素值的名稱
Series . index.name=str 設(shè)置索引的名稱
DataFrame 對象
DataFrame 是一個表格型的數(shù)據(jù)結(jié)構(gòu),它含有一組有序的列,每列可以是不同的值類型(數(shù)值、字符串、布爾型值)。DataFrame 既有行索引也有列索引,它可以被看做由 Series 組成的字典(共同用一個索引)。可以參考 excel 表格
DataFrame 構(gòu)造方法如下:
pandas.DataFrame( data, index, columns, dtype, copy)
參數(shù)說明:
Pandas DataFrame 是一個二維的數(shù)組結(jié)構(gòu),類似二維數(shù)組。
DataFrame 的構(gòu)建
data 為字典類型:
鍵作索引,值作內(nèi)容。
2. 由 Series對象構(gòu)成的字典;
data 為列表類型:
索引
與python列表一樣,在 Series對象 和 DataFrame 對象 中我們同樣可以使用索引來進行數(shù)據(jù)的 增,刪,改,查。
在 pandas 中索引分為以下種:
我們可以通過兩種索引來進行數(shù)據(jù)的增,刪,改,查。
通過索引獲取元素
因為 Pandas 是基于NumPy構(gòu)建的,所以 pandas 可以使用數(shù)組的操作,可以參考數(shù)組的索引來獲取元素值。
import numpy as np import pandas as pd data={'name':'張三','age':20,'class':'三班','sex':'男'} ser=pd.Series(data) print(f'Series對象:\n{ser}') print('獲取單個元素:') print(f'方法一通過下標(biāo) ser[1]:{ser[1]}') print(f"方法二通過標(biāo)簽名 ser['age']:{ser['age']}") print('獲取多個元素:') print(f'方法一通過下標(biāo)與標(biāo)簽名:\n下標(biāo):ser[[1,3]]=\n{ser[[1,3]]}') print(f"標(biāo)簽名:ser[['name','sex']]=\n{ser[['name','sex']]}") print(f"通過下標(biāo)切片:\n{ser[0:3]}") print(f"通過標(biāo)簽名切片:\n{ser['name':'sex']}")Series對象的常用屬性與方法
屬性:
Series. index
Series.values
作用:訪問Series對象的索引值與元素值
import numpy as np import pandas as pd data={'name':'張三','age':20,'class':'三班'} ser=pd.Series(data) print(ser) print('利用 Series 對象的屬性,index和values訪問其索引值與元素值:') print(ser.index) print(ser.values)方法
Series. isnull ( )
Series. notnull ( )
作用:查找缺失值,也就是 nan。
import numpy as np import pandas as pd from pandas.core.indexes.base import Index data={'name':'張三','age':20,'class':'三班'} string='''在使用字典作為數(shù)據(jù)時, 指定索引的個數(shù)可以超出元素值的個數(shù), 多余的索引對應(yīng)值為 nan:''' print(string) ser=pd.Series(data,index=['name','age','class','sex']) print(ser) print(f'isnull()方法判斷Series對象中是否有缺失值 nan,空為True:\n{ser.isnull()}') print(f'notnull()方法與上述類似,這個是非空為True:\n{ser.notnull()}')Series. head ( n : int = 5)
Series. tail ( n : int = 5)
作用:在 Series 對象中從前面取 n 行;從后面取 n 行,默認(rèn) n = 5
Series. unique ( ) - - - >array
作用:去重
Series. value_counts ( ) - - - >Series
作用:檢查每個元素出現(xiàn)的次數(shù)。
import numpy as np import pandas as pd ser=pd.Series([2,5,6,7,4,5,2,3,6,4]) print(ser) print('*'*20) print(ser.unique()) print('*'*20) print(ser.value_counts())DataFrame對象常見的屬性與方法
屬性:
DataFrame. values - - -> 返回一個二維數(shù)組
DataFrame. index - - -> 返回一個Index對象
DataFramecolumns - - -> 返回一個Index對象
方法:
apply與applymap
DataFrame. apply ( func, axis = 0) -> DataFrame
DataFrame. applymap ( func )-> DataFrame
apply 中應(yīng)用對象中于每列或每行的函數(shù) ;applymap中應(yīng)用于對象中每個有元素的函數(shù)。
沿其應(yīng)用功能的軸:
0或’index’:將函數(shù)應(yīng)用于每個縱軸。
1或’columns’:將函數(shù)應(yīng)用于每個橫軸。
apply ( ) 方法同樣適用于 Series 對象。
import numpy as np import pandas as pd df=pd.DataFrame(np.random.randn(4,3)) print(df) df=df.abs() print(f'求每個元素中的絕對值:\n{df}') f=lambda x : x.max() df_apply=df.apply(f) print(f'求每一列中的最大值:\n{df_apply}') f=lambda x:f'{x:.2f}' df_applymap=df.applymap(f) print(f'將每個元素保留兩位小數(shù):\n{df_applymap}')排序方法:
sort_index( axis , ascending)
axis ['?ks?s] : int, default 0
指定軸來直接排序。對于系列,此值只能為0。
ascending [?’send??] 升序:布爾值或布爾值列表,默認(rèn)為True,當(dāng)索引為多索引時,可以單獨控制每個級別的排序方向。
2. 按值排序
sort_values (by , axis , ascending)
by : str or list of str。指定要排序的名稱或名稱列表。
作用:沿任一軸按值排序。
成員關(guān)系判斷
isin ( values )
參數(shù)
values : iterable, Series, DataFrame or dict
返回
DataFrame of booleans 布爾型數(shù)據(jù)框
Series of booleans 布爾型系列
處理缺失數(shù)據(jù)的方法
isnull ( ) - - - > DataFrame of booleans
dropna ( axis = 0)
作用:丟失缺失值所在的行或列。
fillna ( values )
作用:將值 values 填充在 nan 值所在的位置
簡介介紹:
索引操作:
Series 和 DataFrame 中的索引都是 Index 對象。
import numpy as np import pandas as pd arr=np.arange(12).reshape(4,3) ser=pd.Series(range(7)) frame=pd.DataFrame(arr,index=['A','B','C','D'],columns=['a','c','d']) print(f'Series對象的索引類型type(ser.index):\n{type(ser.index)}') print(f'DataFrame對象的索引類型type(frame.index):\n{type(frame.index)}') print(f'type(frame.columns): {type(frame.columns)}')Series. reindex ( )
DataFrame. reindex ( )
增加Series對象的索引:
Series [ new_index ] = value
在原基礎(chǔ)上新增一個
Series. append ( other_Series )
將兩個對象合并成一個新的對象,并不改變原來的對象
增加 DataFrame 對象的索引:
import numpy as np import pandas as pd arr=np.arange(9).reshape(3,3) ser=pd.Series(range(5),index=['a','b','c','d','e']) frame=pd.DataFrame(arr,index=['a','b','c'],columns=['A','B','C']) print(frame) print('默認(rèn)增加 列 :') frame['4']=9 frame['D']=[10,11,12] frame.insert(0,'E',[6,66,666]) print(frame) print('使用標(biāo)簽索引增加 行 :') frame.loc['x']=[1,11,111,111,11,1] print(frame)pandas庫的一些算數(shù)方法
pandas庫的一些統(tǒng)計方法
| count | 非NA值的個數(shù) |
| min , max | 最小值與最大值 |
| idxmin , idxmax | 最小值與最大值的索引值 |
| sum , mean | 總和與平均數(shù) |
| var , std | 樣本值的方差與標(biāo)準(zhǔn)差 |
| cumsum | 樣本值的累計和 |
| cumprod | 樣本值的累計積 |
| cummin , cummax | 樣本值的累計最大值和最小值 |
| describe | 計算匯總統(tǒng)計 |
參數(shù):
pandas庫的一些算術(shù)方法
| add , radd | 加法(+) |
| sub , rsub | 減法(-) |
| div , rdiv | 除法(/) |
| floordiv , rfloordiv | 整除(//) |
| mul , rmul | 乘法(*) |
| pow , rpow | 冪次方(**) |
參數(shù)
- fill_value:填充值,將na值填充掉
r:r 代表者翻轉(zhuǎn),即參數(shù)位置互換,除數(shù)變成被除數(shù);被除數(shù)變成除數(shù)。
pandas庫中數(shù)據(jù)的加載與存儲
從電腦中讀取CSV文件:
| read_csv ( ) | 從文件對象中加載帶分隔符的數(shù)據(jù),默認(rèn)逗號為分割符 |
| read_table ( ) | 從文件對象中加載帶分隔符的數(shù)據(jù),默認(rèn)制表符為分割符 |
| read_excel ( ) | 從 excel 中讀取表格數(shù)據(jù) |
參數(shù):
| path | 表示文件對象所在系統(tǒng)位置的字符串 |
| sep | 拆分每行字段的字符串或正則表達(dá)式 |
| header | 默認(rèn)第一行為列索引,若沒有索引時應(yīng)設(shè)置為None |
| index_col | 從列索引中選一個或多個組成列表,當(dāng)作行索引 |
| names | 用于結(jié)果的列名稱,結(jié)合 header = None使用 |
| skipeows | 跳過幾行,(從 0 開始) |
| skip_footer | 忽略幾行,(從文件末尾處算起) |
| nrows | 讀取幾行,(從 0 開始) |
| na_values | 替換 NA 值 |
| iterator | 布爾類型,返回一個TextParser進行迭代讀取 |
| chunksize | 整型,作用同上,兩者結(jié)和文件對象方法 get_chunksize ( ) 使用。 |
將pandas數(shù)據(jù)寫入電腦
DataFrame. to_csv ( path )
path:寫入路徑
數(shù)據(jù)清洗與準(zhǔn)備
刪除缺失數(shù)據(jù)
| isnull | 返回布爾值組成的對象,空為True |
| notnull | 返回布爾值組成的對象,非空為True |
| dropna | 刪除缺失值所在的行或列 |
| fillna | 替換缺失值 |
dropna (axis , how , thresh , inplace )
參數(shù):
刪除缺少值所在的行或列
“any”:只要存在一個NA值,就刪除該行或列。
“all”:只有全部為NA值,才刪除該行或列。
False:返回一個新對象,不改變原對象
True:不返回對象,直接改變原對象。
填充缺失數(shù)據(jù)
fillna ( value , axis , method , inplace , limit )
參數(shù):
pad/ffill:將上一個有效觀察向前傳播到下一個有效觀察,
backfill / bfill:使用下一個有效觀測值填充間隙。
如果指定了method方法,則這是要向前/向后填充的連續(xù)NaN值的最大數(shù)目。
如果未指定method方法,則這是沿整個軸填充NAN的最大條目數(shù)。
如果不是無,則必須大于0。
替換數(shù)據(jù)
replace ( to_replace , value , method , inplace , limit )
作用:將對象內(nèi)的值 to_replace 用指定值 value 進行替換
刪除重復(fù)項
drop_duplicates ( subset , keep , inplace , ignore_index) - - -> DataFrame
參數(shù):
以選中的列為標(biāo)準(zhǔn),進行去重
‘first’:除去第一次出現(xiàn)的重復(fù)項。
‘last’:刪除除最后一次出現(xiàn)之外的重復(fù)項。
False:刪除所有重復(fù)項。
軸索引的重命名:
區(qū)分:方法 reindex ( ) 只能調(diào)整索引的順序,而不能改變索引的名稱。
import numpy as np import pandas as pd df=pd.DataFrame(np.arange(12).reshape(3,4),index=['BeiJing','Tokyo','New York'],columns=['one','two','three','four']) print(df) print('*'*20) print(df.reindex(['BeiJing','New York','Tokyo'])) print('*'*20) print(df.reindex(['a','b','c']))
改變索引的名稱:
rename ( index , columns , inplace)
import numpy as np from numpy.core.defchararray import index import pandas as pd df=pd.DataFrame(np.arange(12).reshape(3,4),index=['BeiJing','Tokyo','New York'],columns=['one','two','three','four']) print(df) print('*'*20) print(df.rename(index=str.title,columns=str.upper)) print('*'*20) print(df.rename(index={'Tokyo':'東京'},columns={'three':'第三年'}))數(shù)據(jù)清洗總結(jié):
| 異常數(shù)據(jù) | 刪除異常數(shù)據(jù)所在的行 | drop ( ) | |
| NA值問題 | 填充或刪除 | isnull ( ) | fillna( ) , dropna( ) |
| 重復(fù)數(shù)據(jù) | 刪除重復(fù)數(shù)據(jù) | duplicated ( ) | drop_duplicates ( ) |
| 數(shù)據(jù)類型變更 | 變更數(shù)據(jù)類型,指定新類型 | astype ( ) | |
| 部分?jǐn)?shù)據(jù)包含數(shù)值和字符串 | 進行字符串操作, | map ( ) | |
| 不利于分析的數(shù)據(jù) | 替換數(shù)據(jù)元素 | replace ( ) |
數(shù)據(jù)規(guī)整
層次化索引
數(shù)據(jù)連接
DataFrame. merge ( left , right , how=‘inner’ , on=None , left_on=None , right_on = None )
未完待續(xù)!!!!!
總結(jié)
以上是生活随笔為你收集整理的pandas的一些理解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java中的character_什么是J
- 下一篇: Pygame实战:这款“欢乐打地鼠”小游