日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達者為師

網(wǎng)站首頁 編程語言 正文

numpy中的converters和usecols用法詳解_python

作者:溫欣' ? 更新時間: 2022-07-27 編程語言

用Python打開Excel數(shù)據(jù),讀取時需要將”學(xué)號“和“ID"轉(zhuǎn)換成字符,以便后續(xù)操作

df = pd.read_excel(path, converters={'學(xué)號': str, 'ID': str})

在這里插入圖片描述

以下是我的經(jīng)歷來體會:

我在從Excel讀入python的數(shù)據(jù)時,發(fā)現(xiàn)讀出的是空值:

import pandas as pd 
df=pd.read_excel("D:/Python/05DataMineML/2022STU(1).xlsx")
df

在這里插入圖片描述

但是分明是有數(shù)據(jù)的,大概率出現(xiàn)的原因是sheetname(表的名稱)出現(xiàn)了問題。

那就試試其他的方法:

下圖是Excel的表頭,共有115行數(shù)據(jù)。

在這里插入圖片描述

方法一:使用usecols

#獲取字段的第一種寫法
import pandas as pd
df=pd.read_excel('../05DataMineML/2022STU(1).xlsx',usecols=['學(xué)號','姓名','20220101','20220125','20220202','20220208','20220213','20220220','20220226','20220311','20220320','20220327','20220403','randscore'],index_col='姓名',sheet_name='2022STUMOOC')
df.info()

index_col:指定作為表格的索引值
usecols:pandas讀取excel使用read_excel()中的usecols參數(shù)讀取指定的列
sheet_name:表名

在這里插入圖片描述

重點:要使用usecols參數(shù),sheet_name必須顯式寫出來。

在這里插入圖片描述

方法二:使用numpy

#獲取字段的第二種寫法:使用numpy
import pandas as pd
import numpy as np
df=pd.read_excel('../05DataMineML/2022STU(1).xlsx',converters={'學(xué)號':str},usecols=np.arange(3,16),index_col='姓名',sheet_name='2022STU')
df.head()

這里就涉及converters:

converters={'學(xué)號':str}:將學(xué)號轉(zhuǎn)換為字符類型,以便后續(xù)操作。

在這里插入圖片描述

這里使用了usecols=np.arange(3,16)

在這里插入圖片描述

方法三:使用切片區(qū)間

#獲取字段的第三種寫法:切片區(qū)間
import pandas as pd
import numpy as np
df=pd.read_excel('../05DataMineML/2022STUMOOC (1).xlsx',converters={'學(xué)號':str},usecols=("D:P"),index_col='姓名',sheet_name='2022STUMOOC')
df

這里使用了usecols=("D:P"),也就是使用了如下圖每列的序號值做切片

在這里插入圖片描述

在這里插入圖片描述

總結(jié):

converters用法:轉(zhuǎn)換類型。比如將Excel數(shù)據(jù)一列從int變成str

usecols用法

usecols=[‘學(xué)號',‘姓名']
usecols=np.arange(3,16)
usecols=(“D:P”)

原文鏈接:https://blog.csdn.net/wxfighting/article/details/123953013

欄目分類
最近更新