吐血整理python數據分析利器pandas的八個生命周期!

来源:https://www.cnblogs.com/lwsbc/archive/2022/10/20/16811149.html
-Advertisement-
Play Games

在筆者之前的文章`《驅動開發:內核特征碼搜索函數封裝》`中我們封裝實現了特征碼定位功能,本章將繼續使用該功能,本次我們需要枚舉內核`LoadImage`映像回調,在Win64環境下我們可以設置一個`LoadImage`映像載入通告回調,當有新驅動或者DLL被載入時,回調函數就會被調用從而執行我們自己... ...


這裡從八個pandas的數據處理生命周期,整理彙總出pandas框架在整個數據處理過程中都是如何處理數據的。

【閱讀全文】

也就是從pandas的數據表對象以及數據彙總、數據統計等等直到數據導出的八個處理過程來完成pandas使用的彙總處理。

首先,需要準備好將python非標準庫導入進來,除了pandas之外一般伴隨數據分析處理使用的還有numpy科學計算庫。

# Importing the pandas library and giving it the alias pd.
import pandas as pd

# Importing the numpy library and giving it the alias np.
import numpy as np

1、數據表對象(DataFrame)

在pandas的數據分析處理中,主要依賴的是對DataFrame對象的處理來完成數據的提取、彙總、統計等操作。

那麼在初始化DataFrame對象的時候有兩種方式,一種是直接讀取Excel、csv文件獲取數據後返回DataFrame數據對象。

# Reading the csv file and converting it into a dataframe.
dataframe_csv = pd.DataFrame(pd.read_csv('./data.csv'))

# Reading the excel file and converting it into a dataframe.
dataframe_xlsx = pd.DataFrame(pd.read_excel('./data.xlsx'))

另一種則是需要自己創建DataFrame對象的數據,將字典等類型的python對象直接初始化為DataFrame數據表的形式。

# Creating a dataframe with two columns, one called `name` and the other called `age`.
dataframe = pd.DataFrame({"編程語言": ['Java', 'Python', 'C++'],
                          "已誕生多少年": [23, 20, 28]},
                         columns=['編程語言', '已誕生多少年'])

2、數據表(DataFrame)結構信息

通過DataFrame對象內置的各種函數來查看數據維度、列名稱、數據格式等信息。

# Creating a dataframe with two columns, one called `name` and the other called `age`.
dataframe = pd.DataFrame({"編程語言": ['Java', 'Python', 'C++'],
                          "已誕生多少年": [23, 20, 28]},
                         columns=['編程語言', '已誕生多少年'])

【加粗】dataframe.info()

查看數據表的基本信息展示,包括列數、數據格式、列名稱、占用空間等。

dataframe.info()

# <class 'pandas.core.frame.DataFrame'>
# Index: 0 entries
# Data columns (total 2 columns):
#  #   Column  Non-Null Count  Dtype
# ---  ------  --------------  -----
#  0   編程語言    0 non-null      object
#  1   已誕生多少年  0 non-null      object
# dtypes: object(2)
# memory usage: 0.0+ bytes

【加粗】dataframe.columns

查看DataFrame對象的所有列的名稱,並返回數組信息。

print('顯示所有列的名稱是:{0}'.format(dataframe.columns))

# 顯示所有列的名稱是:Index(['編程語言', '已誕生多少年'], dtype='object')

【加粗】dataframe['列名'].dtype

查看DataFrame對象中某一列的格式dtype是什麼。

print('列名(編程語言)的格式是:{0}'.format(dataframe[u'編程語言'].dtype))

# 列名(編程語言)的格式是:object

【加粗】dataframe.shape

通過DataFrame對象的shape函數,進而展示出數據是幾行幾列的結構。

print('dataframe的結構是:{0}'.format(dataframe.shape))

# dataframe的結構是:(3, 2)

【加粗】dataframe.values

使用DataFrame對象的values函數,得出所有數據內容的結果。

# Importing the pprint function from the pprint module.
from pprint import pprint

pprint('dataframe對象的值是:{0}'.format(dataframe.values))

# "dataframe對象的值是:[['Java' 23]\n ['Python' 20]\n ['C++' 28]]"

3、數據清洗

數據清洗即是對DataFrame對象中的數據進行規範化的處理,比如空值的數據填充、重覆數據的清理、數據格式的統一轉換等等。

【加粗】dataframe.fillna()

# 將所有數據為空的項填充為0
dataframe.fillna(value=0)

# 使用均值進行填充
dataframe[u'已誕生多少年'].fillna(dataframe[u'已誕生多少年'].mean())

【加粗】map(str.strip)

# 去除指定列的首尾多餘的空格後,再重新賦值給所在列

dataframe[u'編程語言'] = dataframe[u'編程語言'].map(str.strip)

【加粗】dataframe.astype

# 更改DataFrame數據對象中某個列的數據格式。

dataframe[u'已誕生多少年'].astype('int')

【加粗】dataframe.rename

# 更改DataFrame數據對象中某個列的名稱

dataframe.rename(columns={u'已誕生多少年': u'語言年齡'})

【加粗】 dataframe.drop_duplicates

# 以DataFrame中的某個列為準,刪除其中的重覆項

dataframe[u'編程語言'].drop_duplicates()

【加粗】dataframe.replace

# 替換DataFrame數據對象中某個列中指定的值

dataframe[u'編程語言'].replace('Java', 'C#')

4、數據預梳理

數據預處理(data preprocessing)是指在主要的處理以前對數據進行的一些處理。

如對大部分地球物理面積性觀測數據在進行轉換或增強處理之前,首先將不規則分佈的測網經過插值轉換為規則網的處理,以利於電腦的運算。

【加粗】數據合併

使用DataFrame對象數據合併的有四種方式可以選擇,分別是merge、append、join、concat方式,不同方式實現的效果是不同的。

接下來使用兩種比較常見的方式append、concat、join來演示一下DataFrame對象合併的效果。

使用兩個DataFrame的數據對象通過append將對象的數據內容進行合併。

# Creating a dataframe with two columns, one called `編程語言` and the other called `已誕生多少年`.
dataframeA = pd.DataFrame({"編程語言": ['Java', 'Python', 'C++'],
                           "已誕生多少年": [23, 20, 28]}, columns=['編程語言', '已誕生多少年'])

# Creating a dataframe with two columns, one called `編程語言` and the other called `已誕生多少年`.
dataframeB = pd.DataFrame({"編程語言": ['Scala', 'C#', 'Go'],
                           "已誕生多少年": [23, 20, 28]}, columns=['編程語言', '已誕生多少年'])

# Appending the dataframeB to the dataframeA.
res = dataframeA.append(dataframeB)

# Printing the result of the append operation.
print(res)

#      編程語言  已誕生多少年
# 0    Java      23
# 1  Python      20
# 2     C++      28
# 0   Scala      23
# 1      C#      20
# 2      Go      28
#
# Process finished with exit code 0

使用兩個DataFrame的數據對象通過concat將對象的數據內容進行合併。

# Concatenating the two dataframes together.
res = pd.concat([dataframeA, dataframeB])

# Printing the result of the append operation.
print(res)

#      編程語言  已誕生多少年
# 0    Java      23
# 1  Python      20
# 2     C++      28
# 0   Scala      23
# 1      C#      20
# 2      Go      28

concat函數的合併效果和append函數有異曲同工之妙,兩者同樣都是對數據內容進行縱向合併的。

使用兩個DataFrame的數據對象通過join將對象的數據結構及數據內容進行橫向合併。

# Creating a dataframe with two columns, one called `編程語言` and the other called `已誕生多少年`.
dataframeC = pd.DataFrame({"編程語言": ['Java', 'Python', 'C++'],
                           "已誕生多少年": [23, 20, 28]}, columns=['編程語言', '已誕生多少年'])

# Creating a dataframe with one column called `歷史表現` and three rows.
dataframeD = pd.DataFrame({"歷史表現": ['A', 'A', 'A']})

# Joining the two dataframes together.
res = dataframeC.join(dataframeD, on=None)

# Printing the result of the append operation.
print(res)

#      編程語言  已誕生多少年 歷史表現
# 0    Java      23    A
# 1  Python      20    A
# 2     C++      28    A

可以發現使用join的函數之後,將dataframeD作為一個列擴展了並且對應的每一行都準確的填充了數據A。

【加粗】設置索引

給DataFrame對象設置索引的話就比較方便了,直接DataFrame對象提供的set_index函數設置需要定義索引的列名稱就OK了。

# Creating a dataframe with two columns, one called `編程語言` and the other called `已誕生多少年`.
dataframeE = pd.DataFrame({"編程語言": ['Java', 'Python', 'C++'],
                           "已誕生多少年": [23, 20, 28]}, columns=['編程語言', '已誕生多少年'])

# Setting the index of the dataframe to the column `編程語言`.
dataframeE.set_index(u'編程語言')

# Printing the dataframeE.
print(dataframeE)

#      編程語言  已誕生多少年
# 0    Java      23
# 1  Python      20
# 2     C++      28

【加粗】數據排序

DataFrame數據對象的排序主要是通過索引排序、某個指定列排序的方式為參照完成對DataFrame對象中的整個數據內容排序。

# Sorting the dataframeE by the index.
res = dataframeE.sort_index()

# Printing the res.
print(res)

#      編程語言  已誕生多少年
# 0    Java      23
# 1  Python      20
# 2     C++      28

# Sorting the dataframeE by the column `已誕生多少年`.
res = dataframeE.sort_values(by=['已誕生多少年'], ascending=False)

# Printing the res.
print(res)

#      編程語言  已誕生多少年
# 2     C++      28
# 0    Java      23
# 1  Python      20

sort_index函數是指按照當前DataFrame數據對象的索引進行排序,sort_values則是按照指定的一個或多個列的值進行降序或者升序。

【加粗】數據分組

數據預處理中的數據分組主要是需要的分組的數據打上特殊的標記以便於後期對數據的歸類處理。

比較簡單一些的分組處理可以使用numpy中提供的函數進行處理,這裡使用numpy的where函數來設置過濾條件。

# Creating a new column called `分組標記(高齡/低齡)` and setting the value to `高` if the value in the column `已誕生多少年` is greater
# than or equal to 23, otherwise it is setting the value to `低`.
dataframeE['分組標記(高齡/低齡)'] = np.where(dataframeE[u'已誕生多少年'] >= 23, '高', '低')

# Printing the dataframeE.
print(dataframeE)

#      編程語言  已誕生多少年 分組標記(高齡/低齡)
# 0    Java      23           高
# 1  Python      20           低
# 2     C++      28           高

稍微複雜一些的過濾條件可以使用多條件的過濾方式找出符合要求的數據項進行分組標記。

# Creating a new column called `分組標記(高齡/低齡,是否是Java)` and setting the value to `高/是` if the value in the column `已誕生多少年` is
# greater than or equal to 23 and the value in the column `編程語言` is equal to `Java`, otherwise it is setting the value to
# `低/否`.
dataframeE['分組標記(高齡/低齡,是否是Java)'] = np.where((dataframeE[u'已誕生多少年'] >= 23) & (dataframeE[u'編程語言'] == 'Java'), '高/是',
                                             '低/否')

# Printing the dataframeE.
print(dataframeE)

#      編程語言  已誕生多少年 分組標記(高齡/低齡) 分組標記(高齡/低齡,是否是Java)
# 0    Java      23           高                 高/是
# 1  Python      20           低                 低/否
# 2     C++      28           高                 低/否

5、提取數據

數據提取即是對符合要求的數據完成提取操作,DataFrame對象提取數據主要是按照標簽值、標簽值和位置以及數據位置進行提取。

DataFrame對象按照位置或位置區域提取數據,這裡所說的位置其實就是DataFrame對象的索引。

基本上所有的操作都能夠使用DataFrame對象的loc函數、iloc函數這兩個函數來實現操作。

提取索引為2的DataFrame對象對應的行數據。

# Selecting the row with the index of 2.
res = dataframeE.loc[2]

# Printing the result of the operation.
print(res)

# 編程語言                   C++
# 已誕生多少年                  28
# 分組標記(高齡/低齡)              高
# 分組標記(高齡/低齡,是否是Java)    低/否
# Name: 2, dtype: object

提取索引0到1位置的所有的行數據。

# Selecting the rows with the index of 0 and 1.
res = dataframeE.loc[0:1]

# Printing the result of the operation.
print(res)

#      編程語言  已誕生多少年 分組標記(高齡/低齡) 分組標記(高齡/低齡,是否是Java)
# 0    Java      23           高                 高/是
# 1  Python      20           低                 低/否

按照前兩行前兩列的數據區域提取數據。

# 註意這裡帶有冒號:的iloc函數用法效果是和前面不一樣的。

# Selecting the first two rows and the first two columns.
res = dataframeE.iloc[:2, :2]

# Printing the result of the operation.
print(res)

#      編程語言  已誕生多少年
# 0    Java      23
# 1  Python      20

提取符合條件的數據項,對某一列數據中指定的值完成提取。

# 提取出編程語言這個列中數據內容是Java、C++的數據行。

# Selecting the rows where the value in the column `編程語言` is either `Java` or `C++`.
res = dataframeE.loc[dataframeE[u'編程語言'].isin(['Java', 'C++'])]

# Printing the result of the operation.
print(res)

#    編程語言  已誕生多少年 分組標記(高齡/低齡) 分組標記(高齡/低齡,是否是Java)
# 0  Java      23           高                 高/是
# 2   C++      28           高                 低/否

6、篩選數據

篩選數據是數據處理整個生命周期中的最後一個對原有數據的提取操作,通過各種邏輯判斷條件的操作來完成數據篩選。

這裡分別通過使用DataFrame對象的'與'、'或'、'非'三種常用的邏輯判斷來實現下麵的數據篩選操作。

# Creating a dataframe with two columns, one called `編程語言` and the other called `已誕生多少年`.
dataframeF = pd.DataFrame({"編程語言": ['Java', 'Python', 'C++'],
                           "已誕生多少年": [23, 20, 28]}, columns=['編程語言', '已誕生多少年'])

res = dataframeF.loc[(dataframeF[u'已誕生多少年'] > 25) & (dataframeF[u'編程語言'] == 'C++'), [u'編程語言', u'已誕生多少年']]

# Printing the result of the operation.
print(res)

#   編程語言  已誕生多少年
# 2  C++      28

res = dataframeF.loc[(dataframeF[u'已誕生多少年'] > 23) | (dataframeF[u'編程語言'] == 'Java'), [u'編程語言', u'已誕生多少年']]

# Printing the result of the operation.
print(res)

#    編程語言  已誕生多少年
# 0  Java      23
# 2   C++      28

res = dataframeF.loc[(dataframeF[u'編程語言'] != 'Java'), [u'編程語言', u'已誕生多少年']]

# Printing the result of the operation.
print(res)

#      編程語言  已誕生多少年
# 1  Python      20
# 2     C++      28

7、數據彙總

數據彙總通常是使用groupby函數對一個或多個列名稱進行分組,再使用count函數統計分組後的數目。

res = dataframeF.groupby(u'編程語言').count()

# Printing the result of the operation.
print(res)

#         已誕生多少年
# 編程語言
# C++          1
# Java         1
# Python       1

res = dataframeF.groupby(u'編程語言')[u'已誕生多少年'].count()

# Printing the result of the operation.
print(res)

# 編程語言
# C++       1
# Java      1
# Python    1
# Name: 已誕生多少年, dtype: int64

res = dataframeF.groupby([u'編程語言',u'已誕生多少年'])[u'已誕生多少年'].count()

# Printing the result of the operation.
print(res)

# 編程語言    已誕生多少年
# C++     28        1
# Java    23        1
# Python  20        1
# Name: 已誕生多少年, dtype: int64

8、數據統計

數據統計的概念基本上和數學上的思路是一樣的,首先是對數據進行採樣,採樣完成計算相關的標準差、協方差等相關的數據指標。

'''按照採樣不放回的方式,隨機獲取DataFrame對象中的兩條數據'''
res = dataframeF.sample(n=2, replace=False)

# Printing the result of the operation.
print(res)

#      編程語言  已誕生多少年
# 0    Java      23
# 1  Python      20

可以發現每次執行之後都會隨機的從DataFrame的數據表中取出兩條數據。

若是採樣放回的方式時則可以將replace的屬性設置為True即可。

# 計算出DataFrame對象的所有列的協方差
res = dataframeF.cov()

# Printing the result of the operation.
print(res)

#            已誕生多少年
# 已誕生多少年  16.333333

# 計算出DataFrame對象相關性
res = dataframeF.corr()

# Printing the result of the operation.
print(res)

#         已誕生多少年
# 已誕生多少年     1.0

以上就是Python數據處理中整個生命周期數據的處理過程以及常見的各個數據處理過程中的常見處理方式。

感謝大家一直以來的陪伴,Python集中營將會繼續努力創作出更好的內容,感謝大家的閱讀!

【往期推薦】

python中的精度計算應該用什麼,類似Java中的Bigdecimal對象!

如何將Excel中全國各省份人口數據繪製成地域分佈圖?

周末自製了一個批量圖片水印添加器!

歡迎關註作者公眾號【Python 集中營】,專註於後端編程,每天更新技術乾貨,不定時分享各類資料!
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 寫作不停,美化不止! mac小圓點效果 原本代碼塊樣式就挺....乾凈的,光禿禿的,太單調了: 是吧很醜,於是自己發揮改成了這樣: 好吧還是太單調,也沒好看到哪裡去,於是隔了兩天又重新改,DuangDuangDuang!! 改成了自己想要的樣子,主要的就是喜歡這個mac的三個小圓點,very nic ...
  • 在開發中會遇到這樣的需求:獲取子組件的引用,並調用子組件中定義的方法。如封裝了一個表單組件,在父組件中需要調用這個表單組件的引用,並調用這個表單組件的校驗表單函數或重置表單函數。要實現這個功能,首先要在子組件中暴露父組件需要調用的函數,然後去父組件中獲取子組件的引用,最後通過子組件的引用調用子組件暴 ...
  • 在上一篇中,我們一起分析了 VS Code 整體的代碼架構,瞭解了 VS Code 是由前後端分離的方式開發的。且無論前端是基於 electron 還是 web,後端是本地還是雲端,其調用方式並無不同。 這樣的架構下,前後端的通信方式是如何實現的呢?本篇我們將一起來探究 VS Code For We ...
  • 每年的蘋果新產品發佈,其官網都會配套更新相應的單頁滾動產品介紹頁。其中的動畫特效都非常有意思,今年 iPhone 14 Pro 的介紹頁不例外。 最近,剛好有朋友問到,其對官網的一段文字特效特別感興趣,看適用簡單卻不知從何下手,我們來看看: 整個動畫大致是,隨著頁面的向下滾動,整個文字從無到出現,再 ...
  • call,apply,bind作為改變this指向的法寶,那麼它們是怎麼做到的呢,接下來嘗試邊分析、邊構造: 我們先來構造一個mycall骨架,把功能添加到原型鏈 讓函數依附於某個對象,並且以對象方法的方式執行,以此來改變this指向,需要註意: 為了避免不必要的覆蓋,我們使用Symbol作為key ...
  • 近期,數據中心系統負荷大,mysql伺服器的CPU動輒達到90%以上。代碼和數據表存在很大優化空間。 這裡分享一個定時任務批量處理數據的優化過程。 先介紹定時任務 先介紹下麵2張數據表 欄位 數據量 platform_order 平臺交易訂單表 有超過50多個欄位。 包括 主鍵自增id、客戶id、客 ...
  • 前言 嗨嘍~大家好呀,這裡是魔王吶 ! 國企文員和游戲陪玩兩個職業間,你會選擇哪個? 00後李明的答案是後者。 今年3月,某二本院校應屆畢業生李明,兜兜轉轉,沒有找到特別合心的工作 卻憑著還不錯的游戲技術,成為了全職的游戲陪玩。 “按單收費,大概一單大概兩三百元,按時長收費,一小時50到100元”, ...
  • 滿漢樓02 4.功能實現04 4.6顯示所有菜品 4.6.1思路分析 創建一個菜單表menu,在Domain層創建與菜單表對應的Javabean-Menu類,在DAO層創建MenuDAO,完成對menu表的增刪改查,在Service層創建一個和menu表相關的service類,service類提供給 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...