pandas重新設(shè)置列索引 pandas.dataframe怎么把列變成索引?
pandas.dataframe怎么把列變成索引?在dataframe中根據(jù)一定的條件,得到符合要求的某行元素所在的位置。代碼如下所示:[python] view plain copydf = pd.
pandas.dataframe怎么把列變成索引?
在dataframe中根據(jù)一定的條件,得到符合要求的某行元素所在的位置。
代碼如下所示:
[python] view plain copy
df = pd.DataFrame({"BoolCol": [1, 2, 3, 3, 4],"attr": [22, 33, 22, 44, 66]},
index=[10,20,30,40,50])
print(df)
a = df[(df.BoolCol==3)&(df.attr==22)].index.tolist()
print(a)
df如下所示,以上通過(guò)選取“BoolCol”取值為3且“attr”取值為22的行,得到該行在df中的位置
注意:返回的位置為index列表,根據(jù)index的不同而不同,這點(diǎn)易于數(shù)組中默認(rèn)的下標(biāo)。
[python] view plain copy
BoolCol attr
10 1 22
20 2 33
30 3 22
40 3 44
50 4 66
[30]
pandas中哪個(gè)函數(shù)可以讀取excel文檔excelfilepython?
import xlrddata = xlrd.open_workbook("excelFile.xls")table = data.sheets()[0] #通過(guò)索引順序獲取table = data.sheet_by_index(0) #通過(guò)索引順序獲取table = data.sheet_by_name(u"Sheet1")#通過(guò)名稱獲取
如何用pandas實(shí)現(xiàn)選取特定索引的行?
分享一篇pandas實(shí)現(xiàn)選取特定索引的行的方法,希望對(duì)你有所幫助:
>>> 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ù)組來(lái)訪問(wèn),下標(biāo)又會(huì)從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
>>>
可以試試看