最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python?pandas處理excel表格數(shù)據(jù)的常用方法總結(jié)

 更新時(shí)間:2022年07月25日 13:19:47   作者:地球被支點(diǎn)撬走啦  
在計(jì)算機(jī)編程中,pandas是Python編程語(yǔ)言的用于數(shù)據(jù)操縱和分析的軟件庫(kù),下面這篇文章主要給大家介紹了關(guān)于python?pandas處理excel表格數(shù)據(jù)的常用方法,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下

前言

最近助教改作業(yè)導(dǎo)出的成績(jī)表格跟老師給的名單順序不一致,腦殼一亮就用pandas寫了個(gè)腳本自動(dòng)吧原始導(dǎo)出的成績(jī)謄寫到老師給的名單中了哈哈哈,這里就記錄下用到的pandas處理excel的常用方式。(注意:只適用于.xlsx類型的文件)

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

原始內(nèi)容如下:

a)讀取第n個(gè)Sheet(子表,在左下方可以查看或增刪子表)的數(shù)據(jù)

import pandas as pd
# 每次都需要修改的路徑
path = "test.xlsx"
# sheet_name默認(rèn)為0,即讀取第一個(gè)sheet的數(shù)據(jù)
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
"""

可以注意到,原始表格左上角沒(méi)有填入內(nèi)容,讀取的結(jié)果是“Unnamed: 0” ,這是由于read_excel函數(shù)會(huì)默認(rèn)把表格的第一行為列索引名。另外,對(duì)于行索引名來(lái)說(shuō),默認(rèn)從第二行開始編號(hào)(因?yàn)槟J(rèn)第一行是列索引名,所以默認(rèn)第一行不是數(shù)據(jù)),如果不特意指定,則自動(dòng)從0開始編號(hào),如下。

sheet = pd.read_excel(path)
# 查看列索引名,返回列表形式
print(sheet.columns.values)
# 查看行索引名,默認(rèn)從第二行開始編號(hào),如果不特意指定,則自動(dòng)從0開始編號(hào),返回列表形式
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)讀取時(shí)跳過(guò)第n行的數(shù)據(jù)

# 跳過(guò)第2行的數(shù)據(jù)(第一行索引為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、獲取表格的數(shù)據(jù)大?。簊hape

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、索引數(shù)據(jù)的方法:[ ] / loc[] / iloc[]

1、直接加方括號(hào)索引

可以使用方括號(hào)加列名的方式 [col_name] 來(lái)提取某列的數(shù)據(jù),然后再用方括號(hào)加索引數(shù)字 [index] 來(lái)索引這列的具體位置的值。這里索引名為name1的列,然后打印位于該列第1行(索引是1)位置的數(shù)據(jù):4,如下:

sheet = pd.read_excel(path)
# 讀取列名為 name1 的列數(shù)據(jù)
col = sheet['name1']
print(col)
# 打印該列第二個(gè)數(shù)據(jù)
print(col[1]) # 4
"""
0    1
1    4
2    7
Name: name1, dtype: int64
4
"""

2、iloc方法,按整數(shù)編號(hào)索引

使用 sheet.iloc[ ] 索引,方括號(hào)內(nèi)為行列的整數(shù)位置編號(hào)(除去作為行索引的那一列和作為列索引的哪一行后,從 0 開始編號(hào))。
a)sheet.iloc[1, 2] :提取第2行第3列數(shù)據(jù)。第一個(gè)是行索引,第二個(gè)是列索引

b)sheet.iloc[0: 2] :提取前兩行數(shù)據(jù)

c)sheet.iloc[0:2, 0:2] :通過(guò)分片的方式提取 前兩行前兩列 數(shù)據(jù)

# 指定第一列數(shù)據(jù)為行索引
sheet = pd.read_excel(path, index_col=0)
# 讀取第2行(row2)的第3列(6)數(shù)據(jù)
# 第一個(gè)是行索引,第二個(gè)是列索引
data = sheet.iloc[1, 2]
print(data)  # 6
print('================================')
# 通過(guò)分片的方式提取 前兩行 數(shù)據(jù)
data_slice = sheet.iloc[0:2]
print(data_slice)
print('================================')
# 通過(guò)分片的方式提取 前兩行 的 前兩列 數(shù)據(jù)
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[ ] 索引,方括號(hào)內(nèi)為行列的名稱字符串。具體使用方式同 iloc ,只是把 iloc 的整數(shù)索引替換成了行列的名稱索引。這種索引方式用起來(lái)更直觀。

注意iloc[1: 2] 是不包含2的,但是 loc['row1': 'row2'] 是包含 'row2' 的。

# 指定第一列數(shù)據(jù)為行索引
sheet = pd.read_excel(path, index_col=0)
# 讀取第2行(row2)的第3列(6)數(shù)據(jù)
# 第一個(gè)是行索引,第二個(gè)是列索引
data = sheet.loc['row2', 'name3']
print(data)  # 1
print('================================')
# 通過(guò)分片的方式提取 前兩行 數(shù)據(jù)
data_slice = sheet.loc['row1': 'row2']
print(data_slice)
print('================================')
# 通過(guò)分片的方式提取 前兩行 的 前兩列 數(shù)據(jù)
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、判斷數(shù)據(jù)為空:np.isnan() / pd.isnull()

1、使用 numpy 庫(kù)的 isnan() pandas 庫(kù)的 isnull() 方法判斷是否等于 nan 。

sheet = pd.read_excel(path)
# 讀取列名為 name1 的列數(shù)據(jù)
col = sheet['name2']
 
print(np.isnan(col[1]))  # True
print(pd.isnull(col[1]))  # True
"""
True
True
"""

2、使用 str() 轉(zhuǎn)為字符串,判斷是否等于 'nan' 

sheet = pd.read_excel(path)
# 讀取列名為 name1 的列數(shù)據(jù)
col = sheet['name2']
print(col)
# 打印該列第二個(gè)數(shù)據(jù)
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、查找符合條件的數(shù)據(jù)

下面的代碼意會(huì)一下吧

# 提取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、增加數(shù)據(jù):[ ]

增加列,直接使用中括號(hào) [ 要添加的名字 ] 添加。

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、刪除數(shù)據(jù):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 行,刪除列的話對(duì)應(yīng)的 axis=1。

當(dāng) inplace 參數(shù)為 True 時(shí),不會(huì)返回參數(shù),直接在原數(shù)據(jù)上刪除

當(dāng) inplace 參數(shù)為 False (默認(rèn))時(shí)不會(huì)修改原數(shù)據(jù),而是返回修改后的數(shù)據(jù)

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=[ ] 參數(shù)可以刪除多行或多列

# 刪除多列,默認(rèn) inplace 參數(shù)位 False,即會(huì)返回結(jié)果
print(sheet.drop(labels=['name1', 'name2'], axis=1))
"""
      name3
row1      3
row2      6
row3      9
"""

9、保存到excel文件:to_excel()

1、把 pandas 格式的數(shù)據(jù)另存為 .xlsx 文件

names = ['a', 'b', 'c']
scores = [99, 100, 99]
result_excel = pd.DataFrame()
result_excel["姓名"] = names
result_excel["評(píng)分"] = scores
# 寫入excel
result_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 結(jié)果如下:

總結(jié)

到此這篇關(guān)于python pandas處理excel表格數(shù)據(jù)的常用方法的文章就介紹到這了,更多相關(guān)pandas處理excel數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

壶关县| 贵德县| 漯河市| 景泰县| 湘潭县| 丽江市| 商洛市| 禄劝| 称多县| 砀山县| 天镇县| 凤翔县| 和龙市| 资阳市| 泰兴市| 长海县| 泸水县| 勐海县| 巨野县| 禹城市| 广平县| 廉江市| 肃南| 贺州市| 朝阳县| 阳西县| 天津市| 元江| 祁东县| 竹北市| 夏邑县| 威海市| 大理市| 体育| 金华市| 咸宁市| 湟中县| 赣榆县| 蓝山县| 深水埗区| 东兰县|