pandas多層索引 如何用pandas實現(xiàn)選取特定索引的行?
如何用pandas實現(xiàn)選取特定索引的行?分享一篇pandas實現(xiàn)選取特定索引的行的方法,希望對你有所幫助:>>> import numpy as np>>> import pa
如何用pandas實現(xiàn)選取特定索引的行?
分享一篇pandas實現(xiàn)選取特定索引的行的方法,希望對你有所幫助:
>>> import numpy as np
>>> import pandas as pd
>>> index=np.array([2,4,6,8,10])
>>> data=np.array([3,5,7,9,11])
>>> data=pd.DataFrame({"num":data},index=index)
>>> print(data)
num
2 3
4 5
6 7
8 9
10 11
>>> select_index=index[index>5]
>>> print(select_index)
[ 6 8 10]
>>> data["num"].loc[select_index]
6 7
8 9
10 11
Name: num, dtype: int32
>>>
注意,不能用iloc,iloc是將序列當(dāng)作數(shù)組來訪問,下標(biāo)又會從0開始:
>>> data["num"].iloc[2:5]
6 7
8 9
10 11
Name: num, dtype: int32
>>> data["num"].iloc[[2,3,4]]
6 7
8 9
10 11
Name: num, dtype: int32
>>>
可以試試看
用pandas導(dǎo)入csv表格后,怎么指定那一列是index?
引入pandas使用pandas下的read_csv方法,讀取csv文件,參數(shù)是文件的路徑,這是一個相對路徑,是相對于當(dāng)前工作目錄的,那么如何知道當(dāng)前的工作目錄呢?使用os.getcwd()方法獲取當(dāng)前工作目錄讀取前三后數(shù)據(jù),查看一下是否讀取正確,顯然都是亂碼,這是什么問題呢?我們需要設(shè)定參數(shù)encoding,也就是編碼方式,如果你不設(shè)定編碼方式,默認是utf8,現(xiàn)在csv文件是gbk編碼的,所以需要使用encoding="gbk"我用的編輯器是eric4,注意,eric4默認是不支持中文的,如果你想要顯示中文,前提是設(shè)置正確的編碼,在preferences中設(shè)置成utf8即可
pandas中哪個函數(shù)可以讀取excel文檔excelfilepython?
import xlrddata = xlrd.open_workbook("excelFile.xls")table = data.sheets()[0] #通過索引順序獲取table = data.sheet_by_index(0) #通過索引順序獲取table = data.sheet_by_name(u"Sheet1")#通過名稱獲取