小白學 Python 資料分析(9):Pandas (八)資料預處理(2)
人生苦短,我用 Python
前文傳送門:
小白學 Python 資料分析(1):資料分析基礎
小白學 Python 資料分析(2):Pandas (一)概述
小白學 Python 資料分析(3):Pandas (二)資料結構 Series
小白學 Python 資料分析(4):Pandas (三)資料結構 DataFrame
小白學 Python 資料分析(5):Pandas (四)基礎操作(1)檢視資料
小白學 Python 資料分析(6):Pandas (五)基礎操作(2)資料選擇
小白學 Python 資料分析(7):Pandas (六)資料匯入
小白學 Python 資料分析(8):Pandas (七)資料預處理
引言
前一篇文章我們介紹了資料預處理中資料有問題的幾種情況以及一般處理辦法。
很經常,當我們拿到資料的時候,首先需要確定拿到的是正確型別的資料,如果資料型別不正確,一般通過資料型別的轉化
資料型別轉化
大家應該都知道 Excel 中資料型別比較多,常用的有文字、數字、貨幣、時間、日期等等,在 Pandas 中,相對而言資料型別就少了很多,常用的有 int64 , float64 , object , datetime64 等等。
還是使用前面的示例,我們先看下當前資料表中的資料型別,這裡使用的 dtypes
,示例如下:
import pandas as pd # 相對路徑 df = pd.read_excel("result_data.xlsx") print(df) # 輸出結果 plantform read_num fans_num rank_num like_num create_date 0 cnblog 215.0 0 118.0 0 2019-11-23 23:00:10 1 cnblog 215.0 0 118.0 0 2019-11-23 23:00:10 2 juejin NaN 0 -2.0 1 2019-11-23 23:00:03 3 csdn 1652.0 69 0.0 24 2019-11-23 23:00:02 4 cnblog 650.0 3 NaN 0 2019-11-22 23:00:15 .. ... ... ... ... ... ... 404 juejin 212.0 0 -1.0 2 2020-02-20 23:00:02 405 csdn 1602.0 1 0.0 1 2020-02-20 23:00:01 406 cnblog 19.0 0 41.0 0 2020-02-21 23:00:05 407 juejin 125.0 1 -4.0 0 2020-02-21 23:00:02 408 csdn 1475.0 8 0.0 3 2020-02-21 23:00:02 print(df.dtypes) # 輸出結果 plantform object read_num float64 fans_num int64 rank_num float64 like_num int64 create_date datetime64[ns] dtype: object
當然,我們如果想單獨知道某一列的資料型別,也可以這麼用:
import pandas as pd
# 相對路徑
df = pd.read_excel("result_data.xlsx")
print(df['read_num'].dtypes)
# 輸出結果
float64
當我們需要轉換資料型別的時候,可以使用 astype()
這個方法,在使用的時候講需要轉化的目標型別寫在 astype()
後面括號裡即可:
import pandas as pd # 相對路徑 df = pd.read_excel("result_data.xlsx") print(df['fans_num'].astype('float64')) # 輸出結果 0 0.0 1 0.0 2 0.0 3 69.0 4 3.0 ... 404 0.0 405 1.0 406 0.0 407 1.0 408 8.0 Name: fans_num, Length: 409, dtype: float64
新增索引
有些時候,我們拿到的資料表是沒有索引的,如果沒有索引, Pandas 會預設的為我們新增從 0 開始的自然數作為行索引。而列索引會預設取第一行。比如我們建立了一個沒有表頭的 Excel ,如下:
沒有表頭這樣的資料看起來很難懂,我們先匯入到 Pandas 中看下效果:
import pandas as pd
df1 = pd.read_excel("demo.xlsx")
print(df1)
# 輸出結果
A1 1001 小紅 1000
0 A2 1002 小王 2000
1 A3 1003 小明 3000
2 A4 1004 小朱 4000
3 A5 1005 小黑 5000
這時,我們想給這個資料表加上列索引,這裡可以使用 columns ,如下:
import pandas as pd
df1 = pd.read_excel("demo.xlsx")
df1.columns = ['編號', '序號', '姓名', '消費金額']
print(df1)
# 輸出結果
編號 序號 姓名 消費金額
0 A2 1002 小王 2000
1 A3 1003 小明 3000
2 A4 1004 小朱 4000
3 A5 1005 小黑 5000
現在我們有了列索引,但是如果這時我並不想用自動生成的自然數作為行索引,想替換成資料表中的序號,可以怎麼做呢?
這裡需要使用到的是 set_index()
這個方法,在括號中指明需要使用的列名即可:
import pandas as pd
df1 = pd.read_excel("demo.xlsx")
print(df1.set_index('編號'))
# 輸出結果
序號 姓名 消費金額
編號
A2 1002 小王 2000
A3 1003 小明 3000
A4 1004 小朱 4000
A5 1005 小黑 5000
本篇的內容就到這裡結束了,今天的內容有點短,溜了溜了~~
示例程式碼
老規矩,所有的示例程式碼都會上傳至程式碼管理倉庫 Github 和 Gitee 上,方便大家取用。
示例程式碼-Github
示例程式碼-Gi