目錄
- 前言
- 1、讀取xlsx表格:pd.read_excel()
- 2、獲取表格得數據大小:shape
- 3、索引數據得方法:[ ] / loc[] / iloc[]
- 4、判斷數據為空:np.isnan() / pd.isnull()
- 5、查找符合條件得數據
- 6、修改元素值:replace()
- 7、增加數據:[ ]
- 8、刪除數據:del() / drop()
- 9、保存到excel文件:to_excel()
- 總結
前言
最近助教改作業導出得成績表格跟老師給得名單順序不一致,腦殼一亮就用pandas寫了個自動吧原始導出得成績謄寫到老師給得名單中了哈哈哈,這里就記錄下用到得pandas處理excel得常用方式。(注意:只適用于.xlsx類型得文件)
1、讀取xlsx表格:pd.read_excel()
原始內容如下:
a)讀取第n個Sheet(子表,在左下方可以查看或增刪子表)得數據
import pandas as pd# 每次都需要修改得路徑path = "test.xlsx"# sheet_name默認為0,即讀取第一個sheet得數據sheet = pd.read_excel(path, sheet_name=0)print(sheet)""" Unnamed: 0 name1 name2 name30 row1 1 2.0 31 row2 4 NaN 62 row3 7 8.0 9"""
可以注意到,原始表格左上角沒有填入內容,讀取得結果是“Unnamed: 0” ,這是由于read_excel函數會默認把表格得第一行為列索引名。另外,對于行索引名來說,默認從第二行開始編號(因為默認第一行是列索引名,所以默認第一行不是數據),如果不特意指定,則自動從0開始編號,如下。
sheet = pd.read_excel(path)# 查看列索引名,返回列表形式print(sheet.columns.values)# 查看行索引名,默認從第二行開始編號,如果不特意指定,則自動從0開始編號,返回列表形式print(sheet.index.values)"""['Unnamed: 0' 'name1' 'name2' 'name3'][0 1 2]"""
b)列索引名還可以自定義,如下:
sheet = pd.read_excel(path, names=['col1', 'col2', 'col3', 'col4'])print(sheet)# 查看列索引名,返回列表形式print(sheet.columns.values)""" col1 col2 col3 col40 row1 1 2.0 31 row2 4 NaN 62 row3 7 8.0 9['col1' 'col2' 'col3' 'col4']"""
c)也可以指定第n列為行索引名,如下:
# 指定第一列為行索引sheet = pd.read_excel(path, index_col=0)print(sheet)""" name1 name2 name3row1 1 2.0 3row2 4 NaN 6row3 7 8.0 9"""
d)讀取時跳過第n行得數據
# 跳過第2行得數據(第一行索引為0)sheet = pd.read_excel(path, skiprows=[1])print(sheet)""" Unnamed: 0 name1 name2 name30 row2 4 NaN 61 row3 7 8.0 9"""
2、獲取表格得數據大小:shape
path = "test.xlsx"# 指定第一列為行索引sheet = pd.read_excel(path, index_col=0)print(sheet)print('==========================')print('shape of sheet:', sheet.shape)""" name1 name2 name3row1 1 2.0 3row2 4 NaN 6row3 7 8.0 9==========================shape of sheet: (3, 3)"""
3、索引數據得方法:[ ] / loc[] / iloc[]
1、直接加方括號索引
可以使用方括號加列名得方式 [col_name] 來提取某列得數據,然后再用方括號加索引數字 [index] 來索引這列得具體位置得值。這里索引名為name1得列,然后打印位于該列第1行(索引是1)位置得數據:4,如下:
sheet = pd.read_excel(path)# 讀取列名為 name1 得列數據col = sheet['name1']print(col)# 打印該列第二個數據print(col[1]) # 4"""0 11 42 7Name: name1, dtype: int644"""
2、iloc方法,按整數編號索引
使用 sheet.iloc[ ] 索引,方括號內為行列得整數位置編號(除去作為行索引得那一列和作為列索引得哪一行后,從 0 開始編號)。
a)sheet.iloc[1, 2] :提取第2行第3列數據。第一個是行索引,第二個是列索引
b)sheet.iloc[0: 2] :提取前兩行數據
c)sheet.iloc[0:2, 0:2] :通過分片得方式提取 前兩行 得 前兩列 數據
# 指定第一列數據為行索引sheet = pd.read_excel(path, index_col=0)# 讀取第2行(row2)得第3列(6)數據# 第一個是行索引,第二個是列索引data = sheet.iloc[1, 2]print(data) # 6print('================================')# 通過分片得方式提取 前兩行 數據data_slice = sheet.iloc[0:2]print(data_slice)print('================================')# 通過分片得方式提取 前兩行 得 前兩列 數據data_slice = sheet.iloc[0:2, 0:2]print(data_slice)"""6================================ name1 name2 name3row1 1 2.0 3row2 4 NaN 6================================ name1 name2row1 1 2.0row2 4 NaN"""
3、loc方法,按行列名稱索引
使用 sheet.loc[ ] 索引,方括號內為行列得名稱字符串。具體使用方式同 iloc ,只是把 iloc 得整數索引替換成了行列得名稱索引。這種索引方式用起來更直觀。
注意:iloc[1: 2] 是不包含2得,但是 loc['row1': 'row2'] 是包含 'row2' 得。
# 指定第一列數據為行索引sheet = pd.read_excel(path, index_col=0)# 讀取第2行(row2)得第3列(6)數據# 第一個是行索引,第二個是列索引data = sheet.loc['row2', 'name3']print(data) # 1print('================================')# 通過分片得方式提取 前兩行 數據data_slice = sheet.loc['row1': 'row2']print(data_slice)print('================================')# 通過分片得方式提取 前兩行 得 前兩列 數據data_slice1 = sheet.loc['row1': 'row2', 'name1': 'name2']print(data_slice1)"""6================================ name1 name2 name3row1 1 2.0 3row2 4 NaN 6================================ name1 name2row1 1 2.0row2 4 NaN"""
4、判斷數據為空:np.isnan() / pd.isnull()
1、使用 numpy 庫得 isnan() 或 pandas 庫得 isnull() 方法判斷是否等于 nan 。
sheet = pd.read_excel(path)# 讀取列名為 name1 得列數據col = sheet['name2'] print(np.isnan(col[1])) # Trueprint(pd.isnull(col[1])) # True"""TrueTrue"""
2、使用 str() 轉為字符串,判斷是否等于 'nan' 。
sheet = pd.read_excel(path)# 讀取列名為 name1 得列數據col = sheet['name2']print(col)# 打印該列第二個數據if str(col[1]) == 'nan': print('col[1] is nan')"""0 2.01 NaN2 8.0Name: name2, dtype: float64col[1] is nan"""
5、查找符合條件得數據
下面得代碼意會一下吧
# 提取name1 == 1 得行mask = (sheet['name1'] == 1)x = sheet.loc[mask]print(x)""" name1 name2 name3row1 1 2.0 3"""
6、修改元素值:replace()
sheet['name2'].replace(2, 100, inplace=True) :把 name2 列得元素 2 改為元素 100,原位操作。
sheet['name2'].replace(2, 100, inplace=True)print(sheet)""" name1 name2 name3row1 1 100.0 3row2 4 NaN 6row3 7 8.0 9"""
sheet['name2'].replace(np.nan, 100, inplace=True) :把 name2 列得空元素(nan)改為元素 100,原位操作。
import numpy as np sheet['name2'].replace(np.nan, 100, inplace=True)print(sheet)print(type(sheet.loc['row2', 'name2']))""" name1 name2 name3row1 1 2.0 3row2 4 100.0 6row3 7 8.0 9"""
7、增加數據:[ ]
增加列,直接使用中括號 [ 要添加得名字 ] 添加。
sheet['name_add'] = [55, 66, 77] :添加名為 name_add 得列,值為[55, 66, 77]
path = "test.xlsx"# 指定第一列為行索引sheet = pd.read_excel(path, index_col=0)print(sheet)print('====================================')# 添加名為 name_add 得列,值為[55, 66, 77]sheet['name_add'] = [55, 66, 77]print(sheet)""" name1 name2 name3row1 1 2.0 3row2 4 NaN 6row3 7 8.0 9==================================== name1 name2 name3 name_addrow1 1 2.0 3 55row2 4 NaN 6 66row3 7 8.0 9 77"""
8、刪除數據:del() / drop()
a)del(sheet['name3']) :使用 del 方法刪除
sheet = pd.read_excel(path, index_col=0)# 使用 del 方法刪除 'name3' 得列del(sheet['name3'])print(sheet)""" name1 name2row1 1 2.0row2 4 NaNrow3 7 8.0"""
b)sheet.drop('row1', axis=0)
使用 drop 方法刪除 row1 行,刪除列得話對應得 axis=1。
當 inplace 參數為 True 時,不會返回參數,直接在原數據上刪除
當 inplace 參數為 False (默認)時不會修改原數據,而是返回修改后得數據
sheet.drop('row1', axis=0, inplace=True)print(sheet)""" name1 name2 name3row2 4 NaN 6row3 7 8.0 9"""
c)sheet.drop(labels=['name1', 'name2'], axis=1)
使用 label=[ ] 參數可以刪除多行或多列
# 刪除多列,默認 inplace 參數位 False,即會返回結果print(sheet.drop(labels=['name1', 'name2'], axis=1))""" name3row1 3row2 6row3 9"""
9、保存到excel文件:to_excel()
1、把 pandas 格式得數據另存為 .xlsx 文件
names = ['a', 'b', 'c']scores = [99, 100, 99]result_excel = pd.DataFrame()result_excel["姓名"] = namesresult_excel["評分"] = scores# 寫入excelresult_excel.to_excel('test3.xlsx')
2、把改好得 excel 文件另存為 .xlsx 文件。
比如修改原表格中得 nan 為 100 后,保存文件:
import numpy as np # 指定第一列為行索引sheet = pd.read_excel(path, index_col=0)sheet['name2'].replace(np.nan, 100, inplace=True)sheet.to_excel('test2.xlsx')
打開 test2.xlsx 結果如下:
總結
到此這篇關于python pandas處理excel表格數據得常用方法得內容就介紹到這了,更多相關pandas處理excel數據內容請搜索之家以前得內容或繼續瀏覽下面得相關內容希望大家以后多多支持之家!