首頁  >  文章  >  後端開發  >  如何用Python的Pandas函式庫處理Excel資料?

如何用Python的Pandas函式庫處理Excel資料?

WBOY
WBOY轉載
2023-05-08 21:49:183311瀏覽

1、讀取xlsx表格:pd.read_excel()

原始內容如下:

如何用Python的Pandas函式庫處理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  name3
0       row1      1    2.0      3
1       row2      4    NaN      6
2       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  col4
0  row1     1   2.0     3
1  row2     4   NaN     6
2  row3     7   8.0     9
['col1' 'col2' 'col3' 'col4']
"""

c)也可以指定第n列為行索引名 ,如下:

# 指定第一列为行索引
sheet = pd.read_excel(path, index_col=0)
print(sheet)
"""
      name1  name2  name3
row1      1    2.0      3
row2      4    NaN      6
row3      7    8.0      9
"""

d)讀取時跳過第n行的資料

# 跳过第2行的数据(第一行索引为0)
sheet = pd.read_excel(path, skiprows=[1])
print(sheet)
"""
  Unnamed: 0  name1  name2  name3
0       row2      4    NaN      6
1       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  name3
row1      1    2.0      3
row2      4    NaN      6
row3      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    1
1    4
2    7
Name: name1, dtype: int64
4
"""

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)  # 6
print('================================')
# 通过分片的方式提取 前两行 数据
data_slice = sheet.iloc[0:2]
print(data_slice)
print('================================')
# 通过分片的方式提取 前两行 的 前两列 数据
data_slice = sheet.iloc[0:2, 0:2]
print(data_slice)
"""
6
================================
      name1  name2  name3
row1      1    2.0      3
row2      4    NaN      6
================================
      name1  name2
row1      1    2.0
row2      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)  # 1
print('================================')
# 通过分片的方式提取 前两行 数据
data_slice = sheet.loc['row1': 'row2']
print(data_slice)
print('================================')
# 通过分片的方式提取 前两行 的 前两列 数据
data_slice1 = sheet.loc['row1': 'row2', 'name1': 'name2']
print(data_slice1)
"""
6
================================
      name1  name2  name3
row1      1    2.0      3
row2      4    NaN      6
================================
      name1  name2
row1      1    2.0
row2      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]))  # True
print(pd.isnull(col[1]))  # True
"""
True
True
"""

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.0
1    NaN
2    8.0
Name: name2, dtype: float64
col[1] is nan
"""

5、找出符合條件的資料

下面的程式碼義會一下吧

# 提取name1 == 1 的行
mask = (sheet['name1'] == 1)
x = sheet.loc[mask]
print(x)
"""
      name1  name2  name3
row1      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  name3
row1      1  100.0      3
row2      4    NaN      6
row3      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  name3
row1      1    2.0      3
row2      4  100.0      6
row3      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  name3
row1      1    2.0      3
row2      4    NaN      6
row3      7    8.0      9
====================================
      name1  name2  name3  name_add
row1      1    2.0      3        55
row2      4    NaN      6        66
row3      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  name2
row1      1    2.0
row2      4    NaN
row3      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  name3
row2      4    NaN      6
row3      7    8.0      9
"""

c)sheet.drop(labels=['name1', 'name2'], axis=1)

使用label=[ ] 參數可以刪除多行或多列

# 删除多列,默认 inplace 参数位 False,即会返回结果
print(sheet.drop(labels=['name1', 'name2'], axis=1))
"""
      name3
row1      3
row2      6
row3      9
"""

9、儲存到excel檔案:to_excel()

1、把pandas 格式的資料儲存為.xlsx 檔案

#
names = ['a', 'b', 'c']
scores = [99, 100, 99]
result_excel = pd.DataFrame()
result_excel["姓名"] = names
result_excel["评分"] = scores
# 写入excel
result_excel.to_excel('test3.xlsx')

如何用Python的Pandas函式庫處理Excel資料?

 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資料?

#

以上是如何用Python的Pandas函式庫處理Excel資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除