Python中的pandas模塊詳解
概述
在上一節(jié),我們介紹了Python的numpy模塊,包括:多維數(shù)組、數(shù)組索引、數(shù)組操作、數(shù)學(xué)函數(shù)、線性代數(shù)、隨機(jī)數(shù)生成等內(nèi)容。在這一節(jié),我們將介紹Python的pandas模塊。pandas模塊是Python編程語言中用于數(shù)據(jù)處理和分析的強(qiáng)大模塊,它提供了許多用于數(shù)據(jù)操作和清洗的函數(shù),使得數(shù)據(jù)處理和分析變得更為簡單和直觀。
在Python中使用pandas模塊,需要先安裝pandas庫??梢酝ㄟ^pip命令進(jìn)行安裝:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pandas。安裝完成后,就可以在Python腳本中導(dǎo)入pandas模塊,并使用其函數(shù)和方法了。
Series
Series是一個(gè)一維數(shù)組,它不僅包含數(shù)據(jù),還包含索引。Series可以被看作是一個(gè)字典,其中的索引是鍵,值是數(shù)據(jù)。每個(gè)索引只有一個(gè)對應(yīng)的值,因此Series可以被看作是具有標(biāo)簽化的數(shù)值數(shù)據(jù)。
import pandas as pd # 創(chuàng)建一個(gè)Series s = pd.Series([1, 2, 3, 4, 5]) # 輸出: # 0 1 # 1 2 # 2 3 # 3 4 # 4 5 # dtype: int64 print(s)
上面的示例代碼創(chuàng)建了一個(gè)包含五個(gè)整數(shù)的Series,默認(rèn)情況下,它的索引是從0開始的整數(shù)。
當(dāng)然,我們也可以提供一個(gè)列表作為Series的索引和值。
import pandas as pd # 創(chuàng)建一個(gè)帶有自定義索引和值的Series index = ['C', 'S', 'D', 'N', 'P'] s = pd.Series([1, 2, 3, 4, 5], index = index) # 輸出: # C 1 # S 2 # D 3 # N 4 # P 5 # dtype: int64 print(s)
我們還可以直接使用字典創(chuàng)建帶有自定義數(shù)據(jù)標(biāo)簽的數(shù)據(jù),pandas會(huì)自動(dòng)把字典的鍵作為數(shù)據(jù)標(biāo)簽,字典的值作為相對應(yīng)的數(shù)據(jù)。
import pandas as pd # 創(chuàng)建一個(gè)帶有自定義索引和值的Series s = pd.Series({'C': 1, 'S': 2, 'D': 3, 'N': 4, 'P': 5}) # 輸出: # C 1 # S 2 # D 3 # N 4 # P 5 # dtype: int64 print(s)
如果想訪問Series里的數(shù)據(jù),也非常簡單,直接使用中括號加數(shù)據(jù)標(biāo)簽的方式即可。
import pandas as pd s = pd.Series([1, 2, 3, 4, 5]) # 訪問第二個(gè)元素,輸出:3 print(s[2]) s = pd.Series({'C': 1, 'S': 2, 'D': 3, 'N': 4, 'P': 5}) # 訪問Key值為'D'的元素,輸出:3 print(s['D'])
使用Series,結(jié)合pandas強(qiáng)大的數(shù)據(jù)對齊功能,可以讓我們快速對數(shù)據(jù)進(jìn)行分析和處理。
import pandas as pd s1 = pd.Series({'Red': 1, 'Blue': 2, 'Green': 3}) s2 = pd.Series({'Red': 100, 'Blue': 200, 'Green': 300}) s = s1 + s2 # 將兩個(gè)Series進(jìn)行相加,輸出: # Red 101 # Blue 202 # Green 303 # dtype: int64 print(s) s1 = pd.Series({'Red': 1, 'Blue': 2, 'Green': 3, 'White': 4}) s2 = pd.Series({'Red': 100, 'Blue': 200, 'Green': 300}) s = s1 + s2 # 數(shù)據(jù)標(biāo)簽不相同的數(shù)據(jù),運(yùn)算后結(jié)果是NaN,輸出: # Blue 202.0 # Green 303.0 # Red 101.0 # White NaN # dtype: float64 print(s) # 數(shù)據(jù)標(biāo)簽不相同的數(shù)據(jù),調(diào)用add函數(shù),可以設(shè)置默認(rèn)填充值,輸出: # Blue 202.0 # Green 303.0 # Red 101.0 # White 4.0 # dtype: float64 s = s1.add(s2, fill_value = 0) print(s)
DataFrame
DataFrame是一個(gè)二維的表格型數(shù)據(jù)結(jié)構(gòu),類似于Excel或數(shù)據(jù)庫中的表。DataFrame中的數(shù)據(jù)可以是不同的數(shù)據(jù)類型,比如:整數(shù)、浮點(diǎn)數(shù)、字符串、布爾值等。
import pandas as pd # 創(chuàng)建DataFrame data = {'Name': ['Jack', 'Tank', 'John'], 'Age': [20, 21, 19]} df = pd.DataFrame(data) # 輸出: # Name Age # 0 Jack 20 # 1 Tank 21 # 2 John 19 print(df)
使用DataFrame,我們可以很方便地對表中的行、列進(jìn)行增刪改查等操作。使用df['column_name']可以查看指定列的數(shù)據(jù);使用df.iloc[row_number]可以查看指定行的數(shù)據(jù);使用df.loc[row_label]可以基于標(biāo)簽訪問指定行的數(shù)據(jù);使用df[condition]可以篩選出滿足條件的數(shù)據(jù):使用df['new_column'] = values可以添加一個(gè)新列;使用del df['column_name']可以刪除一列。
import pandas as pd # 創(chuàng)建DataFrame data = {'Name': ['Jack', 'Tank', 'John'], 'Age': [20, 21, 19]} df = pd.DataFrame(data) # 輸出: # Name Age # 0 Jack 20 # 1 Tank 21 # 2 John 19 print(df) df = pd.DataFrame(data, index = ['First', 'Second', 'Third']) # 指定自定義索引,輸出: # Name Age # First Jack 20 # Second Tank 21 # Third John 19 print(df) # 訪問列數(shù)據(jù),輸出: # First Jack # Second Tank # Third John # Name: Name, dtype: object print(df['Name']) # 根據(jù)行索引訪問行數(shù)據(jù),輸出: # Name John # Age 19 # Name: Third, dtype: object print(df.iloc[2]) # 根據(jù)行標(biāo)簽訪問行數(shù)據(jù),輸出: # Name John # Age 19 # Name: Third, dtype: object print(df.loc['Third']) df['Age'] = [22, 18, 20] # 修改列數(shù)據(jù),輸出: # Name Age # First Jack 22 # Second Tank 18 # Third John 20 print(df) df['Gender'] = ['M', 'F', 'F'] # 新增列數(shù)據(jù),輸出: # Name Age Gender # First Jack 22 M # Second Tank 18 F # Third John 20 F print(df) del df['Gender'] # 刪除列數(shù)據(jù),輸出: # Name Age # First Jack 22 # Second Tank 18 # Third John 20 print(df) # 篩選出年齡大于20的數(shù)據(jù),輸出: # Name Age # First Jack 22 print(df[df['Age'] > 20])
數(shù)據(jù)讀取和寫入
使用pandas,可以方便地讀取和寫入各種數(shù)據(jù)格式,比如:CSV、Excel、SQL數(shù)據(jù)庫等。我們以CSV文件的讀寫為例,來理解CSV表格數(shù)據(jù)的讀取和寫入。
import pandas as pd # 創(chuàng)建DataFrame data = {'Name': ['Jack', 'Tank', 'John'], 'Age': [20, 21, 19]} df = pd.DataFrame(data) # 將DataFrame寫入CSV文件 df.to_csv('output.csv', index = False)
在上面的示例代碼中,我們首先創(chuàng)建了一個(gè)名為df的DataFrame,然后使用to_csv函數(shù)將其寫入一個(gè)名為output.csv的CSV文件中。我們將index參數(shù)設(shè)置為False,以避免將DataFrame的索引寫入CSV文件。
to_csv函數(shù)還有其他一些可選參數(shù),包括:
sep:用于指定CSV文件中的分隔符,默認(rèn)是逗號。
header:用于指定是否將DataFrame的列名寫入CSV文件中,默認(rèn)為True。
encoding:用于指定文件的編碼格式,默認(rèn)為UTF-8。
compression:用于指定文件的壓縮格式,默認(rèn)為None。
在下面的示例代碼中,我們讀取了上面保存的名為output.csv的CSV文件,并將其轉(zhuǎn)化為一個(gè)pandas DataFrame。
import pandas as pd # 從CSV文件讀取 df = pd.read_csv('output.csv') # 輸出: # Name Age # 0 Jack 20 # 1 Tank 21 # 2 John 19 print(df)
read_csv函數(shù)還有其他一些可選參數(shù),包括:
sep:指定分隔符,默認(rèn)為逗號。
header:指定行號作為列名,默認(rèn)為0。
index_col:將一列或多列設(shè)為DataFrame的索引。
usecols:返回的列的子集,可以是一個(gè)列表或函數(shù)。
dtype:為每一列設(shè)置數(shù)據(jù)類型。
skiprows:跳過指定的行數(shù)或行號。
na_values:用于識別空值的字符串或字符串列表。
keep_default_na:是否保留默認(rèn)的識別空值的字符串。
到此這篇關(guān)于 Python中的pandas模塊的文章就介紹到這了,更多相關(guān) Python pandas模塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python實(shí)現(xiàn)報(bào)表自動(dòng)化詳解
這篇文章主要介紹了python實(shí)現(xiàn)報(bào)表自動(dòng)化詳解,涉及python讀,寫excel—xlwt常用功能,xlutils 常用功能,xlwt寫Excel時(shí)公式的應(yīng)用等相關(guān)內(nèi)容,具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11Python 解碼Base64 得到碼流格式文本實(shí)例
今天小編就為大家分享一篇Python 解碼Base64 得到碼流格式文本實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01Python使用Slider組件實(shí)現(xiàn)調(diào)整曲線參數(shù)功能示例
這篇文章主要介紹了Python使用Slider組件實(shí)現(xiàn)調(diào)整曲線參數(shù)功能,結(jié)合實(shí)例形式分析了Python使用matplotlib與Slider組件進(jìn)行圖形繪制相關(guān)操作技巧,需要的朋友可以參考下2019-09-09pycharm 設(shè)置項(xiàng)目的根目錄教程
今天小編就為大家分享一篇pycharm 設(shè)置項(xiàng)目的根目錄教程,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02Python實(shí)現(xiàn)批量讀取HDF多波段柵格數(shù)據(jù)并繪制像元直方圖
這篇文章主要為大家詳細(xì)介紹了如何基于Python語言gdal模塊,實(shí)現(xiàn)多波段HDF柵格圖像文件的讀取、處理與像元值可視化(直方圖繪制)等操作,需要的可以參考一下2023-03-03