Python使用Pandas庫常見操作詳解
本文實例講述了Python使用Pandas庫常見操作。分享給大家供大家參考,具體如下:
1、概述
Pandas 是Python的核心數(shù)據(jù)分析支持庫,提供了快速、靈活、明確的數(shù)據(jù)結(jié)構(gòu),旨在簡單、直觀地處理關(guān)系型、標(biāo)記型數(shù)據(jù)。Pandas常用于處理帶行列標(biāo)簽的矩陣數(shù)據(jù)、與 SQL 或 Excel 表類似的表格數(shù)據(jù),應(yīng)用于金融、統(tǒng)計、社會科學(xué)、工程等領(lǐng)域里的數(shù)據(jù)整理與清洗、數(shù)據(jù)分析與建模、數(shù)據(jù)可視化與制表等工作。
數(shù)據(jù)類型:Pandas 不改變原始的輸入數(shù)據(jù),而是復(fù)制數(shù)據(jù)生成新的對象,有普通對象構(gòu)成的一維數(shù)組成為Series,由Series構(gòu)成的二維數(shù)組表稱為DataFrame,其行被稱為index,列為Colum。
安裝:如果使用anaconda集成環(huán)境則會自動安裝numpy、scipy、pandas等數(shù)據(jù)科學(xué)包,也可以通過python包管理工具安裝pandas:
pip install pandas
2、數(shù)據(jù)對象的創(chuàng)建
通過Series()函數(shù)包裹一維數(shù)組可以創(chuàng)建Series對象,其中數(shù)組的元素可以是各種類型。
通過DataFrame()函數(shù)包裹二維數(shù)組可以創(chuàng)建一個DataFrame對象,可以通過參數(shù)index、columns指定行標(biāo)簽和列標(biāo)簽。也可以通過python的字典類型初始化DataFrame,其鍵名默認(rèn)為列標(biāo)簽
import pandas as pd import numpy as np # 通過一維數(shù)組初始化Series s = pd.Series([1, 2.0, np.nan, 'test']) print(s) # 通過二維數(shù)組初始化DataFrame arr = np.random.randn(6, 4) arr_df = pd.DataFrame(arr, index=np.arange(1, 7), columns=list('ABCD')) print(arr_df) # 通過字典dict初始化DataFrame dic = {'A': 1., 'B': pd.Timestamp('20130102'), 'C': pd.Series(1, index=list(range(4)), dtype='float32'), 'D': np.array([3] * 4, dtype='int32'), 'E': pd.Categorical(["test", "train", "test", "train"]) } dic_df = pd.DataFrame(dic) print(dic_df)
其運行結(jié)果如下:
# Series數(shù)據(jù) 0 1 1 2 2 NaN 3 test dtype: object # 二維數(shù)組的DataFrame A B C D 1 -0.085417 -0.816502 1.495134 -0.277742 2 1.657144 -0.203346 0.631930 -1.182239 3 -2.303923 -0.535696 1.315379 0.129682 4 0.133198 -0.239664 -2.004494 0.119965 5 -1.454717 2.114255 -0.538678 -0.580361 6 -0.759183 0.141554 -0.243270 2.840325 # dict字典DataFrame A B C D E 0 1.0 2013-01-02 1.0 3 test 1 1.0 2013-01-02 1.0 3 train 2 1.0 2013-01-02 1.0 3 test 3 1.0 2013-01-02 1.0 3 train
3、查看數(shù)據(jù)
函數(shù)head(n)可以查看DataFrame前n行的數(shù)據(jù),tail(n)查看倒數(shù)n行的數(shù)據(jù)
index()查看DataFrame的行標(biāo)簽,columns顯示列標(biāo)簽
describe()按列顯示數(shù)據(jù)的統(tǒng)計信息,包括計數(shù)、均值、方差、最小最大值等。
函數(shù)mean()顯示所有列的均值,mean(1)顯示所有行的均值
sum()求所有列的均值,sum(1)求所有行的均值
DataFrame有一個empty屬性用于判斷是否為空,若為空則返回True
arr = np.random.randn(6, 4) df = pd.DataFrame(arr, index=np.arange(1, 7), columns=list('ABCD')) print(df.head(3)) print(df.index) print(df.describe())
結(jié)果如下
# 查看前三行數(shù)據(jù) A B C D 1 3.260449 -0.619396 0.070877 1.586914 2 -0.529708 0.071917 -1.919316 1.845727 3 -1.005765 2.176579 -0.323483 -1.295067 # 查看行標(biāo)簽 Int64Index([1, 2, 3, 4, 5, 6], dtype='int64') # 查看統(tǒng)計信息 A B C D count 6.000000 6.000000 6.000000 6.000000 mean -0.184606 -0.487184 0.079433 0.855810 std 1.721394 1.800460 1.379498 1.128764 min -1.443635 -3.091446 -1.919316 -1.295067 25% -0.967105 -1.430192 -0.281188 0.778729 50% -0.694488 -0.273739 -0.041713 1.150944 75% -0.531744 0.197755 0.355731 1.508475 max 3.260449 2.176579 2.352142 1.845727
4、數(shù)據(jù)的選擇
可以直接通過DataFrame對象選取列或者行,
# 選取一個列A,等價于df['A'] print(df.A) # 選取第1到第3行,行下標(biāo)從0開始 print(df[1:3]) ''' # 標(biāo)簽為A的那一列 1 0.644427 2 0.643149 3 1.374668 4 -0.154465 5 -0.338085 6 -1.989284 Name: A, dtype: float64 # 第1~3行 A B C D 2 0.643149 1.769001 -0.166028 -0.036854 3 1.374668 -0.118593 -0.202222 0.308353 '''
通過loc[]方法可以通過標(biāo)簽對DataFrame的一行、一列、幾行幾列或者是某個具體的值進(jìn)行選擇
# 取出行標(biāo)簽為2的那一行 print(df.loc[2]) # 取出行標(biāo)簽為1~3,列標(biāo)簽為'A','B'的內(nèi)容 print(df.loc[1:3, ['A', 'B']]) # 獲取行標(biāo)簽為1,列標(biāo)簽為'A'的具體值,等價于df.at[1,'A'] print(df.loc[1, 'A']) ''' # 標(biāo)簽為2的一行 A 0.681469 B -0.053046 C -1.384877 D -0.447700 Name: 2, dtype: float64 # 標(biāo)簽為1~3,列標(biāo)簽為'A','B'的內(nèi)容 A B 1 0.710907 -0.950896 2 0.681469 -0.053046 3 0.781981 0.123072 # 行標(biāo)簽為1,列標(biāo)簽為'A'的具體值 0.7109074858947351 '''
除了通過行列標(biāo)簽來進(jìn)行取值以外,還可以通過行列的數(shù)組的位置進(jìn)行取值,其方法名為iloc[]
# 取出第一行,行下標(biāo)從0開始 print(df.iloc[0]) # 顯示第1,2,4行的第0,2列 print(df.iloc[[1, 2, 4], [0, 2]]) # 顯示第1行第1列的具體值,等價于df.iat[1,1] print(df.iloc[1, 1])
還可以在選擇時對數(shù)據(jù)進(jìn)行過濾
# 輸出A那一列大于0的所有行 print(df[df.A > 0]) df['E'] = ['one', 'one', 'two', 'three', 'four', 'three'] # 輸出E那一列存在two、four的所有行 print(df[df['E'].isin(['two', 'four'])]) ''' A B C D 3 0.168998 -0.732362 -0.098542 0.413128 5 0.513677 -0.163231 -0.098037 -0.606693 A B C D E 3 0.168998 -0.732362 -0.098542 0.413128 two 5 0.513677 -0.163231 -0.098037 -0.606693 four '''
5、操作數(shù)據(jù)
通過insert()方法可以實現(xiàn)在指定位置插入一列,也可以直接將一個數(shù)組賦值給DataFrame,這將默認(rèn)添加到最后一列
可以通過之前的選擇方法loc、iloc找到指定的行列,然后直接賦值,如果該位置存在數(shù)據(jù)則會修改,否則添加
通過drop()方法刪除指定的數(shù)據(jù),index屬性指定刪除的行,columns指定刪除的列,inplace屬性是否在原數(shù)據(jù)集上操作,默認(rèn)為False,此時需要一個變量來接收刪除后的結(jié)果
df = pd.DataFrame(data = [['lisa','f',22],['joy','f',22],['tom','m','21']], index = [1,2,3],columns = ['name','sex','age']) citys = ['ny','zz','xy'] #在第0列,加上column名稱為city,值為citys的數(shù)值。 df.insert(0,'city',citys) jobs = ['student','AI','teacher'] # 默認(rèn)在df最后一列加上column名稱為job,值為jobs的數(shù)據(jù)。 df['job'] = jobs # 若df中沒有index為“4”的這一行的話,則添加,否則修改 df.loc[4] = ['zz', 'mason', 'm', 24, 'engineer'] print(df) # 刪除行標(biāo)簽為1的行 dp=df.drop(index=1) print(dp) # 在原數(shù)據(jù)集上刪除列標(biāo)簽為sex的列 df.drop(columns=['sex'],inplace=True) print(df)
結(jié)果如下:
# 添加后的數(shù)據(jù) city name sex age job 1 ny lisa f 22 student 2 zz joy f 22 AI 3 xy tom m 21 teacher 4 zz mason m 24 engineer # 刪除第一行 city name sex age job 2 zz joy f 22 AI 3 xy tom m 21 teacher 4 zz mason m 24 engineer # 刪除sex列 city name age job 1 ny lisa 22 student 2 zz joy 22 AI 3 xy tom 21 teacher 4 zz mason 24 engineer
對DataFrame進(jìn)行轉(zhuǎn)置操作,調(diào)用.T
sort_index(axis=1, ascending=False)對數(shù)據(jù)進(jìn)行排序,axis=0代表按行標(biāo)簽排序,axis=1代表按列標(biāo)簽排序
sort_values(by='A')按某一列的值對數(shù)據(jù)進(jìn)行排序,這里是按列標(biāo)簽為A的
apply()函數(shù)對DataFrame的每一行應(yīng)用函數(shù)
print(df.T) si=df.sort_index(axis=1, ascending=False) print(si) sv=df.sort_values(by='A') print(sv) # 應(yīng)用匿名函數(shù),用每一列最大值減去最小值 df.apply(lambda x: x.max() - x.min()) print(df) ''' # 數(shù)據(jù)轉(zhuǎn)置 1 2 3 4 5 6 A -1.176180 -1.301768 0.907088 -1.528101 1.098978 -1.280193 B -0.461954 -0.749642 1.169118 -0.297765 0.531088 -0.999842 C -1.715094 -0.512856 0.511861 -0.247240 1.696772 -0.902995 D 1.336999 0.209091 2.254337 0.649625 -0.049886 -1.514815 # 按列標(biāo)簽倒序 D C B A 1 1.336999 -1.715094 -0.461954 -1.176180 2 0.209091 -0.512856 -0.749642 -1.301768 3 2.254337 0.511861 1.169118 0.907088 4 0.649625 -0.247240 -0.297765 -1.528101 5 -0.049886 1.696772 0.531088 1.098978 6 -1.514815 -0.902995 -0.999842 -1.280193 # 按列A的值遞增對行排序 A B C D 4 -1.528101 -0.297765 -0.247240 0.649625 2 -1.301768 -0.749642 -0.512856 0.209091 6 -1.280193 -0.999842 -0.902995 -1.514815 1 -1.176180 -0.461954 -1.715094 1.336999 3 0.907088 1.169118 0.511861 2.254337 5 1.098978 0.531088 1.696772 -0.049886 # 函數(shù)的應(yīng)用 A 2.073961 B 2.671590 C 1.785291 D 0.000000 F 4.000000 dtype: float64 '''
panda的concat函數(shù)可以將兩個相同類型的DataFrame在行的維度上進(jìn)行拼接
merge()函數(shù)可以將不同DataFrame按列拼接
append()函數(shù)可以在DataFrame的結(jié)尾追加
# 將第一行和最后一行拼接 print(pd.concat([df[:1], df[-2:-1]])) # 將第4行追加到結(jié)尾 print(df.append(df.iloc[3])) # 將兩個DataFrame按列拼接 df1 = pd.DataFrame({'row1': ['foo', 'bar'], 'row2': [1, 2]}) df2 = pd.DataFrame({'row1': ['foo', 'bar'], 'row3': [4, 5]}) print(pd.merge(df1, df2)) ''' # 按行拼接 A B C D 1 -0.527221 -0.754650 -2.385270 -2.569586 5 0.054059 1.443911 -0.240856 -1.501045 # 追加 A B C D 1 -0.527221 -0.754650 -2.385270 -2.569586 2 2.123332 -0.013431 -0.574359 -0.548838 3 -0.244057 -0.267805 1.089026 -0.022174 4 -0.789228 1.171906 0.526318 0.046655 5 0.054059 1.443911 -0.240856 -1.501045 6 0.756844 0.623305 -0.597299 0.034326 4 -0.789228 1.171906 0.526318 0.046655 # 按列拼接 row1 row2 row3 0 foo 1 4 1 bar 2 5 '''
groupby函數(shù)可以數(shù)據(jù)按列進(jìn)行分組,分組后的結(jié)果可以使用for循環(huán)進(jìn)行迭代,迭代中每個分組是一個(index,DataFrame)元組,可以對其中的DataFrame作進(jìn)一步操作。
stack()可以將多列的數(shù)據(jù)壓縮為兩列顯示
df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar'], 'B': ['one', 'two', 'one', 'three'], 'C': np.random.randn(4), 'D': np.random.randn(4)}) # 按A、B兩列進(jìn)行分組 dg=df.groupby(['A', 'B']) for (index,df) in dg: print(df) # 壓縮 print(df.stack()) ''' # 按列分組 A B C D 3 bar three 0.802027 1.338614 A B C D 1 bar two -0.567295 0.608978 A B C D 0 foo one -0.17592 -0.191991 2 foo one -0.72258 0.711312 # 壓縮為兩列 0 A foo B one C 0.622471 D 0.10633 1 A bar B two C 0.065516 D -0.844223 2 A foo B one C 0.0013226 D -1.3328 3 A bar B three C -0.678077 D 0.785117 dtype: object '''
Pandas主要使用值np.nan來表示缺失的數(shù)據(jù)??梢允褂胐ropna(how='any')方法來刪除所有存在空值的行,dropna(axis=1)刪除存在空值的列。fillna(value=x)用指定值x填充所有的空值。
6、其他
通過pandas可以便捷地從其他格式文件進(jìn)行轉(zhuǎn)換
# 將DataFrame寫入csv文件 df.to_csv('foo.csv') # 從csv文件讀數(shù)據(jù) df = pd.read_csv('foo.csv') # excel文件的讀寫 df = pd.read_excel('foo.xlsx', 'Sheet1', index_col=None, na_values=['NA']) df.to_excel('foo.xlsx', sheet_name='Sheet1')
pandas提供了便捷的時間維度生成函數(shù)date_range(),第一個參數(shù)是起始時間,periods=生成的數(shù)量,freq=時間間隔,默認(rèn)以天為單位
# 從2019年1月1日開始,以秒為單位,生成五個時間 rng = pd.date_range('1/1/2019', periods=5, freq='S') ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng) print(ts) ''' 2019-01-01 00:00:01 161 2019-01-01 00:00:02 214 2019-01-01 00:00:03 110 2019-01-01 00:00:04 265 Freq: S, dtype: int32 '''
pandas結(jié)合matplot可以便捷地進(jìn)行數(shù)據(jù)繪圖
ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng) # 將數(shù)據(jù)追加到一個數(shù)組統(tǒng)一顯示 ts=ts.cumsum() # 調(diào)用matplot繪制圖 ts.plot()
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)學(xué)運算技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
使用keras根據(jù)層名稱來初始化網(wǎng)絡(luò)
這篇文章主要介紹了使用keras根據(jù)層名稱來初始化網(wǎng)絡(luò),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python項目實戰(zhàn)之使用Django框架實現(xiàn)支付寶付款功能
這篇文章主要介紹了Python項目實戰(zhàn)之使用Django框架實現(xiàn)支付寶付款功能,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02Python創(chuàng)建Excel表和讀取Excel表的基本操作
這篇文章主要介紹了Python創(chuàng)建Excel表和讀取Excel表的基本操作,文中通過代碼示例和圖文結(jié)合的方式講解的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-07-07VSCode Python開發(fā)環(huán)境配置的詳細(xì)步驟
這篇文章主要介紹了VSCode Python開發(fā)環(huán)境配置的詳細(xì)步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02