Python 中pandas索引切片讀取數(shù)據(jù)缺失數(shù)據(jù)處理問題
引入
numpy已經(jīng)能夠幫助我們處理數(shù)據(jù),能夠結(jié)合matplotlib解決我們數(shù)據(jù)分析的問題,那么pandas學(xué)習(xí)的目的在什么地方呢? numpy能夠幫我們處理處理數(shù)值型數(shù)據(jù),但是這還不夠 很多時(shí)候,我們的數(shù)據(jù)除了數(shù)值之外,還有字符串,還有時(shí)間序列等 比如:我們通過爬蟲獲取到了存儲(chǔ)在數(shù)據(jù)庫(kù)中的數(shù)據(jù) 比如:之前youtube的例子中除了數(shù)值之外還有國(guó)家的信息,視頻的分類(tag)信息,標(biāo)題信息等 所以,numpy能夠幫助我們處理數(shù)值,但是pandas除了處理數(shù)值之外(基于numpy),還能夠幫助我們處理其他類型的數(shù)據(jù)。
什么是pandas?
pandas是一個(gè)Python軟件包,提供快速,靈活和富于表現(xiàn)力的數(shù)據(jù)結(jié)構(gòu),旨在使使用“關(guān)系”或“標(biāo)記”數(shù)據(jù)既簡(jiǎn)單又直觀。它旨在成為在Python中進(jìn)行實(shí)際,真實(shí)世界數(shù)據(jù)分析的基本高級(jí)構(gòu)建塊。此外,其更廣泛的目標(biāo)是成為任何語(yǔ)言中可用的最強(qiáng)大,最靈活的開源數(shù)據(jù)分析/操作工具。它已經(jīng)朝著這個(gè)目標(biāo)邁進(jìn)了。
pandas的常用數(shù)據(jù)類型
1、Series 一維,帶標(biāo)簽數(shù)組
2、DataFrame 二維,Series容器
(1)Series創(chuàng)建
pandas.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)
data:類數(shù)組,可迭代,字典或標(biāo)量值,包含存儲(chǔ)在系列中的數(shù)據(jù)。在0.23.0版中進(jìn)行了更改:如果data是dict,則將為Python 3.6及更高版本維護(hù)參數(shù)順序。
index:類數(shù)組或索引(1d)值必須是可散列的,并且與data的長(zhǎng)度相同。允許使用非唯一索引值。如果未提供,則默認(rèn)為RangeIndex(0,1,2,…,n)。如果同時(shí)使用了字典和索引序列,則索引將覆蓋在字典中找到的鍵。
dtype:STR,numpy.dtype,或ExtensionDtype,可選
輸出系列的數(shù)據(jù)類型。如果未指定,則將從data推斷出來。
copy:bool,默認(rèn)為False,copy輸入數(shù)據(jù)。
import pandas as pd import numpy as np t = pd.Series(np.arange(12),index= list("asdfghjklpoi")) print(t) print(type(t))
注意幾個(gè)問題:pd.Series能干什么,能夠傳入什么數(shù)據(jù)類型讓其變?yōu)閟eries結(jié)構(gòu)。index是什么,在什么位置,對(duì)于我們常見的數(shù)據(jù)庫(kù)數(shù)據(jù)或者ndarray來說,index到底是什么如何給一組數(shù)據(jù)指定index。
c = {"name":"lishuntao","age":18,"gender":"boy"} t1 = pd.Series(c) print(t1) print(type(t1)) print(t1["name"]) print(t1["gender"])
從上面可以看出,通過字典創(chuàng)建一個(gè)Series,字典的鍵就是索引。
重新給其綁定其他的索引之后,如果能夠?qū)?yīng)的上,就取其值,如果不能,就為Nan。如圖所示:
import numpy as np import pandas as pd a = {"a":12,"name":"lishuntao","c":"xiaoc","age":18,"gender":"man"} t1 = pd.Series(a) print(t1) print(type(t1)) t2 = pd.Series(a,index=list("abcdf")) print(t2)
numpy中的nan為float,pandas會(huì)自動(dòng)根據(jù)數(shù)據(jù)類型更改series的dtype類型。
Series切片和索引
import numpy as np import pandas as pd a = {"a":12,"name":"lishuntao","c":"xiaoc","age":18,"gender":"man"} t1 = pd.Series(a) print(t1) print(t1[:2]) print(t1[1]) print(t1[["a","c","gender"]]) print(t1[0:5:2])
import numpy as np import pandas as pd a = np.arange(12) t1 = pd.Series(a) print(t1) print(t1[t1>9])
Series的索引和值
import numpy as np import pandas as pd a = np.arange(12) t1 = pd.Series(a) #print(t1) print(t1.index) print(t1.values)
import numpy as np import pandas as pd a = np.arange(12) t1 = pd.Series(a) print(t1) print(type(t1.index)) print(type(t1.values))
Series對(duì)象本質(zhì)上有兩個(gè)數(shù)組構(gòu)成,一個(gè)數(shù)組構(gòu)成對(duì)象的鍵(index,索引),一個(gè)數(shù)組構(gòu)成對(duì)象的值(values),鍵--->值。
ndarray的很多方法都可以運(yùn)用與series類型,比如argmax,clip
series具有where方法,但是結(jié)果卻不同(下面是官方文檔給出)
Series.where
(self,cond[,other,inplace,…])Replace values where the condition is False.
a = np.arange(12) t1 = pd.Series(a) print(t1) #替換條件是False的情況 下面兩個(gè)結(jié)果一樣 print(t1.where((t1>8),1)) print(pd.Series.where(t1,(t1>4),1))
pandas之讀取外部數(shù)據(jù)
現(xiàn)在假設(shè)我們有一個(gè)組關(guān)于狗的名字的統(tǒng)計(jì)數(shù)據(jù),那么為了觀察這組數(shù)據(jù)的情況,我們應(yīng)該怎么做呢?
數(shù)據(jù)來源:https://www.kaggle.com/new-york-city/nyc-dog-names/data
我們的這組數(shù)據(jù)存在csv中,我們直接使用pd. read_csv即可
import numpy as np import pandas as pd t2 = pd.read_csv("F:\BaiduNetdiskDownload\youtube_video_data\dogNames2.csv") print(t2) print(type(t2))
和我們想象的有些差別,他是一個(gè)DataFrame,那么接下來我們就來了解這種數(shù)據(jù)類型
但是,還有一個(gè)問題:
對(duì)于數(shù)據(jù)庫(kù)比如mysql或者mongodb中數(shù)據(jù)我們?nèi)绾问褂媚兀?/p>
pd.read_sql(sql_sentence,connection)
那么,mongodb呢?(先用mongodb自己讀出來,然后將它傳入到DataFrame中,就可以實(shí)現(xiàn)讀?。?/p>
(2)DataFrame的創(chuàng)建
pd.DataFrame(data,index,columns,dtype,copy)
參數(shù)比Series多了columns,從中可以看出這是列索引(Index or array-like Column labels to use for resulting frame. Will default to RangeIndex (0, 1, 2, ..., n) if no column labels are provided)
import numpy as np import pandas as pd t2 = pd.DataFrame(np.arange(12).reshape(3,4)) print(t2)
從上面我們可以看出DataFrame對(duì)象既有行索引,又有列索引
行索引:表明不同行,橫向索引,叫index,0軸,axis=0
列索引:表明不同列,縱向索引,叫columns,1軸,axis=1
自定義索引標(biāo)簽:
t2 = pd.DataFrame(np.arange(12).reshape(3,4),index=list("abc"),columns=list("WXYZ")) print(t2)
DataFrame的基礎(chǔ)屬性
t2 = pd.DataFrame(np.arange(12).reshape(3,4),index=list("abc"),columns=list("WXYZ")) print(t2) print(t2.shape)#顯示行數(shù),列數(shù) print(t2.dtypes)#顯示的是列數(shù)據(jù)類型 print(t2.ndim)#數(shù)據(jù)維度2(0,1) print(t2.index)#行索引 print(t2.columns)#列索引 Index(['W', 'X', 'Y', 'Z'], dtype='object') print(t2.values)#對(duì)象值,二維ndarray的數(shù)組
DataFrame整體情況查詢
t2 = pd.DataFrame(np.arange(12).reshape(3,4),index=list("abc"),columns=list("WXYZ")) print(t2) #print(t2.head()) print(t2.head(1))#顯示頭幾行,默認(rèn)5行 print(t2.tail(2))#顯示末尾幾行,默認(rèn)5行 print(t2.info())#相關(guān)信息瀏覽:行數(shù),列數(shù),列索引,列非空值個(gè)數(shù),列類型,列類型,內(nèi)存占用 print(t2.describe())#快速綜合統(tǒng)計(jì)結(jié)果:計(jì)數(shù),均值,標(biāo)準(zhǔn)差,最大值,四分位數(shù),最小值
動(dòng)手:那么回到之前我們讀取的狗名字統(tǒng)計(jì)的數(shù)據(jù)上,我們嘗試一下剛剛的方法
那么問題來了:
肯定想知道使用次數(shù)最高的前幾個(gè)名字是什么呢?
pd.DataFrame.sort_values(by="Count_AnimalName",ascending=False)#ascending=True升序排序 by是對(duì)那一列排序 輸入列索引鍵 t2 = pd.read_csv("F:\BaiduNetdiskDownload\youtube_video_data\dogNames2.csv") print(t2) t3 = t2.sort_values(by="Count_AnimalName",ascending=False) print(t3)
那么問題又來了:
如果我的數(shù)據(jù)有10列,我想按照其中的第1,第3,第8列排序,怎么辦?
pandas之取行或者列
剛剛我們知道了如何給數(shù)據(jù)按照某一行或者列排序,那么現(xiàn)在我們想單獨(dú)研究使用次數(shù)前100的數(shù)據(jù),應(yīng)該如何做?
t2 = pd.read_csv("F:\BaiduNetdiskDownload\youtube_video_data\dogNames2.csv") print(t2) t3 = t2.sort_values(by="Count_AnimalName",ascending=False) print(t3[:100])
我們具體要選擇某一列該怎么選擇呢?t2[" Count_AnimalName "]
我們要同時(shí)選擇行和不同列該怎么辦?(和numpy類似)
pandas之loc取行數(shù)據(jù)
1、t2.loc 通過標(biāo)簽索引行數(shù)據(jù)(標(biāo)簽)
print(t2.loc["a","W"]) print(t2.loc["a",["W","Y"]]) print(type(t2.loc["a",["W","Y"]])) print(t2.loc[["a","b"],["Z","Y"]]) print(t2.loc[:"c",:"Y"]) print(t2.loc["a":"b",["W","Z"]])
2、t2.iloc 通過位置獲取行數(shù)據(jù)(位置)
import numpy as np import pandas as pd t2 = pd.DataFrame(np.arange(12).reshape(3,4),index=list("abc"),columns=list("WXYZ")) print(t2) print(t2.iloc[0:2,0:4]) print(t2.iloc[[0,2],[1,3]]) t2.loc["a","Y"] = 100 #復(fù)制操作 print(t2) t2.iloc[1:2,[1]] = 1000 #復(fù)制操作 print(t2)
pandas之布爾索引(且,或,&,|,)
回到之前狗的名字的問題上,假如我們想找到所有的使用次數(shù)超過800的狗的名字,應(yīng)該怎么選擇?
print(t2[t2["Count_AnimalName"]>800])
回到之前狗的名字的問題上,假如我們想找到所有的使用次數(shù)超過700并且名字的字符串的長(zhǎng)度大于4的狗的名字,應(yīng)該怎么選擇?
print(t2[(t2["Row_Labels"].str.len()>4)&(t2["Count_AnimalName"]>700)])
pandas之字符串方法
缺失數(shù)據(jù)的處理:
觀察這組數(shù)據(jù)
我們的數(shù)據(jù)缺失通常有兩種情況: 一種就是空,None等,在pandas是NaN(和np.nan一樣) 另一種是我們讓其為0(藍(lán)色框中)
對(duì)于NaN的數(shù)據(jù),在numpy中我們是如何處理的?
在pandas中我們處理起來非常容易 判斷數(shù)據(jù)是否為NaN:pd.isnull(df),pd.notnull(df)
處理方式1:刪除NaN所在的行列
dropna (axis=0, how='any', inplace=False)
處理方式2:填充數(shù)據(jù),
t.fillna(t.mean()),t.fiallna(t.median()),t.fillna(0)
處理為0的數(shù)據(jù):t[t==0]=np.nan 當(dāng)然并不是每次為0的數(shù)據(jù)都需要處理 計(jì)算平均值等情況,nan是不參與計(jì)算的,但是0會(huì)
import numpy as np import pandas as pd t2 = pd.DataFrame(np.arange(12).reshape(3,4),index=list("abc"),columns=list("WXYZ")) #print(t2) t2.loc[:"b",["W","Y"]] = np.nan print(t2) print(pd.isnull(t2)) print(pd.notnull(t2)) #print(t2.dropna(axis=0,how="all",inplace=False)) #any只要含NaN就刪除前面規(guī)定的行列,all需要的是行列全部為NAN才能刪除 #填充數(shù)據(jù) #print(t2.fillna(t2.mean())) print(t2) print(t2.fillna(t2.median())) print(t2.fillna(0))
總結(jié)
以上所述是小編給大家介紹的Python 中pandas索引切片讀取數(shù)據(jù)缺失數(shù)據(jù)處理問題,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
相關(guān)文章
用Python解析身份證號(hào)獲取年齡和性別的實(shí)現(xiàn)方法
身份證號(hào)碼包含了豐富的信息,包括生日和性別,Python提供了處理和解析身份證號(hào)的功能,讓我們能夠從中提取出相關(guān)的信息,本文將介紹如何利用Python解析身份證號(hào),獲取持有者的年齡和性別信息,感興趣的朋友可以參考下2023-12-12python如何將文件a.txt的內(nèi)容復(fù)制到b.txt中
這篇文章主要介紹了python如何將文件a.txt的內(nèi)容復(fù)制到b.txt中,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12django使用channels實(shí)現(xiàn)通信的示例
這篇文章主要介紹了django使用channels實(shí)現(xiàn)通信的示例,幫助大家更好的理解和學(xué)習(xí)django框架,感興趣的朋友可以了解下2020-10-10解決python DataFrame 打印結(jié)果不換行問題
這篇文章主要介紹了解決python DataFrame 打印結(jié)果不換行問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-04-04使用Python實(shí)現(xiàn)微信提醒備忘錄功能
最近工作比較繁雜,經(jīng)常忘事,有時(shí)候記了備忘錄結(jié)果卻忘記看備忘錄,但是微信是每天都會(huì)看的,于是就想到寫 一個(gè)基于微信的提醒系統(tǒng)。這篇文章主要介紹了使用Python實(shí)現(xiàn)微信提醒備忘錄功能,需要的朋友可以參考下2018-12-12Pytorch: 自定義網(wǎng)絡(luò)層實(shí)例
今天小編就為大家分享一篇Pytorch: 自定義網(wǎng)絡(luò)層實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-01-01Python利用物理引擎Pymunk編寫一個(gè)解壓小游戲
這篇文章主要為大家詳細(xì)介紹了Python如何利用物理引擎Pymunk編寫一個(gè)解壓小游戲,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以嘗試一下2023-01-01對(duì)于Python的框架中一些會(huì)話程序的管理
這篇文章主要介紹了對(duì)于Python的框架中一些會(huì)話程序的管理,會(huì)話的實(shí)現(xiàn)是Python框架的基本功能,本文主要講述了對(duì)其的一些管理維護(hù)要點(diǎn),需要的朋友可以參考下2015-04-04