欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python使用pandas讀xlsx文件的實(shí)現(xiàn)

 更新時(shí)間:2022年05月10日 09:19:26   作者:生活甜甜好運(yùn)連連  
這篇文章主要介紹了python使用pandas讀xlsx文件的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

使用pandas讀xlsx文件

  • 讀取前n行數(shù)據(jù)
  • 讀取指定數(shù)據(jù)(指定行指定列)
  • 獲取文件行號(hào)和列標(biāo)題
  • 將數(shù)據(jù)轉(zhuǎn)換為字典形式
import pandas as pd
#1.讀取前n行所有數(shù)據(jù)
df1=pd.read_excel('d1.xlsx')#讀取xlsx中的第一個(gè)sheet
data1=df1.head(10)#讀取前10行所有數(shù)據(jù)
data2=df1.values#list【】  相當(dāng)于一個(gè)矩陣,以行為單位
#data2=df.values()   報(bào)錯(cuò):TypeError: 'numpy.ndarray' object is not callable
print("獲取到所有的值:\n{0}".format(data1))#格式化輸出
print("獲取到所有的值:\n{0}".format(data2))
 
#2.讀取特定行特定列
data3=df1.iloc[0].values#讀取第一行所有數(shù)據(jù)
data4=df1.iloc[1,1]#讀取指定行列位置數(shù)據(jù):讀?。?,1)位置的數(shù)據(jù)
data5=df1.iloc[[1,2]].values#讀取指定多行:讀取第一行和第二行所有數(shù)據(jù)
data6=df1.iloc[:,[0]].values#讀取指定列的所有行數(shù)據(jù):讀取第一列所有數(shù)據(jù)
print("數(shù)據(jù):\n{0}".format(data3))
print("數(shù)據(jù):\n{0}".format(data4))
print("數(shù)據(jù):\n{0}".format(data5))
print("數(shù)據(jù):\n{0}".format(data6))
 
#3.獲取xlsx文件行號(hào)、列號(hào)
print("輸出行號(hào)列表{}".format(df1.index.values))#獲取所有行的編號(hào):0、1、2、3、4
print("輸出列標(biāo)題{}".format(df1.columns.values))#也就是每列的第一個(gè)元素
 
#4.將xlsx數(shù)據(jù)轉(zhuǎn)換為字典
data=[]
for i in df1.index.values:#獲取行號(hào)的索引,并對(duì)其遍歷
    #根據(jù)i來(lái)獲取每一行指定的數(shù)據(jù),并用to_dict轉(zhuǎn)成字典
    row_data=df1.loc[i,['id','name','class','data','score',]].to_dict()
    data.append(row_data)
print("最終獲取到的數(shù)據(jù)是:{0}".format(data))
 
#iloc和loc的區(qū)別:iloc根據(jù)行號(hào)來(lái)索引,loc根據(jù)index來(lái)索引。
#所以1,2,3應(yīng)該用iloc,4應(yīng)該有l(wèi)oc

數(shù)據(jù):d1.xlsx

idnameclassdatascore
201901A1Jan-201.3
201902B2Mar-203.4
201903C3May-203.4
201904D1Jan-203.4
201905E1Feb-205.6
201906F1Mar-204.6
201907G1Feb-197.8
201908H2Apr-305.6
201909I3Jan-425.6
201910G4Mar-304.5
201911K5Apr-203.4
201912L6Apr-202.3
201913M4Mar-202.4

運(yùn)行結(jié)果展示

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論